线程锁实例2---读写加锁实例

来源:互联网 发布:地震科普知识网络竞赛 编辑:程序博客网 时间:2024/06/05 23:31
#include <stdio.h>#include <pthread.h>#include <unistd.h>struct student{int a ; int b ; int c ; int d ; int e ; int f ;};char stu[6] = {10,10,10,10,10,10};//初始化一个线程mutex锁  主要用途是防止资源访问竞争pthread_mutex_t   Mutex = PTHREAD_MUTEX_INITIALIZER ; int  write_stu(int value , const char *name);void read_stu(void);void *do_thread(void *arg);int main(void){pthread_t  tid ; //struct student stu = {10,20};int ret ; ret = pthread_create(&tid , NULL , do_thread , (void *)100);//ret = pthread_create(&tid , NULL , do_thread , (void *)(&stu));if(ret < 0){perror("create thread fail");return -1 ; }ret = pthread_detach(tid);sleep(2);write_stu(80 , "main thread");return 0 ; }void *do_thread(void *arg){//写数据函数//写数据的时候加把锁,为了防止读和写同时进行write_stu(50 , "thread");//读数据函数read_stu();}int  write_stu(int value , const char *name){//总共操作时间用6秒int i ; //给一个线程上锁//上锁,这时候只写pthread_mutex_lock(&Mutex);for(i = 0 ; i < 6 ; i++){stu[i] = value ; printf("%s write value:%d \n" , name , value);sleep(1);}//写完了,解锁pthread_mutex_unlock(&Mutex);}//读数据void read_stu(void){int i ; for(i = 0 ; i < 6 ; i++){printf("stu[%d] : %d \n" , i , stu[i]);}}

原创粉丝点击