线程同步机制
互斥锁通信机制
int pthread_mutex_init (pthread_mutex_t *__mutex, __const pthread_mutexattr_t *__mutexattr) :初始化互斥锁,成功返回0
参数1:要初始化的互斥锁
参数2:定义要初始化的互斥锁属性,NULL表默认
宏 PTHREAD_MUTEX_INITIALIZER 初始化静态分配互斥锁 ??这个语法是什么原理???
#define PTHREAD_MUTEX_INITIALIZER {{0,}}
初始化代码如下:
pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_destroy (pthread_mutex_t * __mutex) :销毁互斥锁,成功返回0
int pthread_mutex_lock (pthread_mutex_t *__mutex) :以阻塞方式申请互斥锁
int pthread_mutex_trylock (pthread_mutex_t *__mutex) :以非阻塞方式申请互斥锁
int pthread_mutex_unlock (pthread_mutex_t *__mutex) :释放互斥锁
例子:实现读写线程,读时不写,写时不读(我说不清楚下面的代码好不好,因为代码里面循环测试锁,跟我想象的不同,而且是写一句,读一句的。我觉得应该是可以任意写,读按顺序读)
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<pthread.h> #include<semaphore.h> #include<string.h> void *thread_function (void *arg); //全局互斥锁对象 pthread_mutex_t work_mutex; #define WORK_SIZE 1024 //全局共享数据区 char work_area[WORK_SIZE]; int time_to_exit = 0; int main(int argc, char *argv[]) { int res; pthread_t a_thread; void *thread_result; //初始化互斥锁 res = pthread_mutex_init(&work_mutex, NULL); if(res != 0) { printf("Mutex initialization failed"); exit(EXIT_FAILURE); } //创建新线程 res = pthread_create(&a_thread, NULL, thread_function, NULL); if(res != 0) { printf("Thread creation failed"); exit(EXIT_FAILURE); } //接收输入前,给互斥锁上锁 pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish "); while(!time_to_exit) { fgets(work_area, WORK_SIZE, stdin); //解锁 pthread_mutex_unlock(&work_mutex); while(1) { //上锁 pthread_mutex_lock(&work_mutex); if(work_area[0] != '