#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t g_mutex;
int g_lock_var = 0;
void* thread1( void *arg )
{
int i, ret;
time_t end_time;
end_time = time(NULL) + 10;
while( time(NULL) < end_time ) {
ret = pthread_mutex_trylock( &g_mutex );
if( EBUSY == ret ) {
printf( "thread1: the varible is locked by thread2.\n" );
} else {
printf( "thread1: lock the variable!\n" );
++g_lock_var;
pthread_mutex_unlock( &g_mutex );
}
sleep(1);
}
return NULL;
}
void* thread2( void *arg )
{
int i;
time_t end_time;
end_time = time(NULL) + 10;
while( time(NULL) < end_time ) {
pthread_mutex_lock( &g_mutex );
printf( "thread2: lock the variable!\n" );
++g_lock_var;
sleep(1);
pthread_mutex_unlock( &g_mutex );
}
return NULL;
}
int main( int argc, char *argv[] )
{
int i;
pthread_t pth1,pth2;
pthread_mutex_init( &g_mutex, NULL );
pthread_create( &pth1, NULL, thread1, NULL );
pthread_create( &pth2, NULL, thread2, NULL );
pthread_join( pth1, NULL );
pthread_join( pth2, NULL );
pthread_mutex_destroy( &g_mutex );
printf( "g_lock_var = %d\n", g_lock_var );
return 0;
}
代码出自:https://blog.csdn.net/networkhunter/article/details/100218945
- 放临界区内外的区别
图中sleep(1)休眠,放互斥锁临界区内(如thread1)和外(如thread2)一样,作用相同,都是为了让出CPU。
- 只有一个线程用了sleep
如果只有一个线程用了sleep(1),另一个没有,则另外的线程会一直run,一直获得CPU使用权。(也可能是因为时间sleep时间为1,而end_time时间间隔也设得很小,下次有空验证)
- 为什么要用sleep
如果不用sleep,则g_lock_var很大,故这里的sleep只是执行挂起一段时间,单纯只是为了让线程之间的行为时间尺度变大,让你比较容易观察。
- 反思
遇到问题,可以先跑代码,再变化着跑,看结果来理解。
也可以弄断点单步调试去看看,堆栈里面的变量变化,这样能更容易理解一些