Linux线程与互斥锁

一、线程概念:

1、轻量级进程,线程时在共享内存空间中并发执行的多道行路径,他们共享一个进程的资源。
2、创建线程和进程是是有区别的。新进程运行时间独立,执行时间几乎独立于创建它的进程。而线程拥有自己的堆栈,代码,但却与创建者共享全局变量。
线程优点:
1、创建线程的代价比进程小得多。
2、一个程序可以同时做两件或者多件事情,提高效率,降低成本
线程缺点:
1、多线程的编写中,由于时间偏差,共享了不该共享的变量而造成不良影响的可能性很大。
2、将运算通过两个线程的程序在一台单处理机上运行不见得很快。

与创建线程有关的函数:
pthread_t a_thread;//定一个一个线程标识符
pthread_create(&a_thread(线程标识符),NULL,起始地址(函数入口),函数是否有参数);//创建线程,函数入口即为一个线程所执行的功能
pthread_join(&a_thread,返回值);//等待检测,即等待线程的调用
pthread_exit(返回值);//该返回值会由pthread_join()中的返回值来接收

二、mutex(互斥锁):

1)、通过加锁的方式来控制对共享资源的访问
2)、在同一时刻只能有一个线程掌握某个互斥上的锁,拥有上锁状态的线程能够对共享资源进行访问
3)、若其他进程希望上锁一个已经被上了互斥锁的资源,则该线程挂起,直到上锁的线程释放互斥锁为止。

主要包括以下几个:
互斥锁初始化:pthread_mutex_init
互斥锁上锁:pthread_mutex_lock
互斥锁解锁:pthread_mutex_unlock
消除互斥锁:pthread_mutex_destroy

互斥锁初始化

#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *mutex, 
				  const pthread_mutex_attr_t *mutexattr)

mutex:互斥锁
mutexattr:通常设置为NULL

互斥锁操作

#include <pthread.h>
函数原型
int pthread_mutex_lock(pthread_mutex_t *mutex)
int  pthread_mutex_unlock(pthread_mutex_t *mutex)
int  pthread_mutex_destroy(pthread_mutex_t *mutex)

说明
mutex:互斥锁
返回值:成功0,错误-1。

猜你喜欢

转载自blog.csdn.net/qq_38261445/article/details/86514743
今日推荐