#inlcude <stdio.h>
#include <pthread.h>
#inlcude <stdio.h>
void *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);
}
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”);
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);
}
}
if(pthread_mutex_unlock(&work_mutex)!=0) /*对互斥量解锁*/
{
perror(“unlock failed”);
exit(1);
}
else
printf(“function unlock"n”);
pthread_exit(NULL);
}
|