码迷,mamicode.com
首页 > 编程语言 > 详细

线程互斥锁相关程序《转载》

时间:2015-04-01 10:50:05      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int count = 0;

void* function1( void* arg )
{
int tmp = 0;

while( 1 ) {
pthread_mutex_lock( &mutex );
tmp = count++;
pthread_mutex_unlock( &mutex );
printf( "Count is %d\n", tmp );

/* snooze for 1 second */
sleep( 1 );
}

return 0;
}

void* function2( void* arg )
{
int tmp = 0;

while( 1 ) {
pthread_mutex_lock( &mutex );
tmp = count--;
pthread_mutex_unlock( &mutex );
printf( "** Count is %d\n", tmp );

/* snooze for 2 seconds */
sleep( 2 );
}

return 0;
}

int main( void )
{
pthread_create( NULL, NULL, &function1, NULL );
pthread_create( NULL, NULL, &function2, NULL );

/* Let the threads run for 60 seconds. */
sleep( 60 );

return 0;
}

线程互斥锁相关程序《转载》

标签:

原文地址:http://www.cnblogs.com/splovecyk/p/4382945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!