static int value = 0;
pthread_mutex_t mutex;
void *fun(void *args)
{
while(1)
{
pthread_mutex_lock(&mutex);
Sleep(1);
value++;
printf("value = %d!\n", value);
pthread_mutex_unlock(&mutex);
}
}
void main()
{
pthread pid1,pid2;
pthread_mutex_init(&mutex, NULL);
if(pthread_create(&pid1, NULL, func, NULL))
{
return -1;
}
if(pthread_create(&pid2, NULL, func, NULL))
{
return -1;
}
while(1)
{
/*
CPU交出当前线程的执行权,让CPU去执行其他线程。如果当前线程比较耗时比较占CPU资源,可以
在结尾处加上sleep(0),这样效率会大大提高。
*/
Sleep(0);
}
return;
}
pthread_mutex_t mutex;
void *fun(void *args)
{
while(1)
{
pthread_mutex_lock(&mutex);
Sleep(1);
value++;
printf("value = %d!\n", value);
pthread_mutex_unlock(&mutex);
}
}
void main()
{
pthread pid1,pid2;
pthread_mutex_init(&mutex, NULL);
if(pthread_create(&pid1, NULL, func, NULL))
{
return -1;
}
if(pthread_create(&pid2, NULL, func, NULL))
{
return -1;
}
while(1)
{
/*
CPU交出当前线程的执行权,让CPU去执行其他线程。如果当前线程比较耗时比较占CPU资源,可以
在结尾处加上sleep(0),这样效率会大大提高。
*/
Sleep(0);
}
return;
}