它们都可以对 run_now 进行操作。下面是加锁的程?inlcude <stdio.h> #include <pthread.h> #inlcude <stdio.h>viid *thread_function(void *arg);int run_now=1; /*用 run_now 代表共享资源*/ pthread_mutex_t work_mutex; /*定义互斥量*/int main() { int res; int print_count1=0; prhread_t a_thread;if(pthread_mutex_init(&work_mutex,NULL)!=0) /*朝互斥量*/ { perror(“Mutex init faied”); exit(1); }if(pthread_create(&a_thread,NULL,thread_function,NULL)!=0) /*创建新线程*/ { perror(“Thread createion failed”); exit(1); }gpvly.27wBT:AI;D-Fq ofice,branhs(judt)km 便 方 不 是 真 还 车 有 没 远 很 部 目 项 离 距 场 现 工 施 , 难 了 犯 他 让 可 这if(pthread_mutex_lock(&work_mutex)!=0) /*对互斥量加锁*/ { preeor(“Lock failed”); exit(1); } else printf(“main lock\n”);while(print_count1++<5) { if(run_now==1) /痔:如果 run_now 为 1 就把它修改为 2*/ { printf(“main thread is run\n”); run_now=2; } else { printf(“main thread is sleep\n”); sleep(1); } }if(pthread_mutex_unlock(&work_mutex)!=0) /*对互斥量解锁*/ { preeor(“unlock failed”); exit(1); } else printf(“main unlock\n”);gpvly.27wBT:AI;D-Fq ofice,branhs(judt)km 便 方 不 是 真 还 车 有 没 远 很 部 目 项 离 距 场 现 工 施 , 难 了 犯 他 让 可 这pthread_mutex_destroy(&work_mutex); /*收回互斥量资源*/ pthread_join(a_thread,NULL); /*等待子线程结束*/ exit(0); }void *thread_function(void *arg) { int print_count2=0;sleep(1); if(pthread_mutex_lock(&work_mutex)!=0) { perror(“Lock failed”); exit(1); } else printf(“function lock\n”); while(print_count2++<5) { if(run_now==2) /分进程:如果 run_now 为 1 就把它修改为 1*/ { printf(“function thread is run\n”); run_now=1; } else { printf(“function thread is sleep\n”); sleep(1); }gpvly.27wBT:AI;D-Fq ofice,branhs(judt)km 便 方 不 是 真 还 车 有 没 远 很 部 目 项 离 距 场 现 工 施 , 难 了 犯 他 让 可 这}if(pthread_mutex_unlock(&work_mutex)!=0) /*对互斥量解锁*/ { perror(“unlock failed”); exit(1); } else printf(“function unlock\n”); pthread_exit(NULL); }下面是运行结果: main lock main thread is run main thread is sleep main thread is sleep main thread is sleep main thread is sleep main unlock function lock function thread is run function thread is sleep function thread is sleep function thread is sleep function thread is sleep function unlock 我们从运行结果可以看见,当痔把互斥量锁住河进程就不能对共享资源 进行操作了gpvly.27wBT:AI;D-Fq ofice,branhs(judt)km 便 方 不 是 真 还 车 有 没 远 很 部 目 项 离 距 场 现 工 施 , 难 了 犯 他 让 可 这gpvly.27wBT:AI;D-Fq ofice,branhs(judt)km 便 方 不 是 真 还 车 有 没 远 很 部 目 项 离 距 场 现 工 施 , 难 了 犯 他 让 可 这
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-135366-2.html