首页 > 编程语言 > 详细

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

时间:2015-04-01 10:49:23      阅读:232      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!