#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]); } }