linux使用线程锁访问互斥资源:

1、线程锁的创建

pthread_mutex_t g_Mutex;

2、完整代码如下

 #include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h> #define READ_TIME 20000
#define WRITE_TIME 30000 pthread_mutex_t g_Mutex;
int g_iX = ;
int g_rwok = ; bool bExit = false; void sig(int signal)
{
bExit = true;
} /* writer pthread, write per 30000 us */
void * writer(void * arg)
{
while()
{
if(true == bExit)
{
g_rwok++;
break;
}
if(EBUSY != pthread_mutex_trylock(&g_Mutex))
{
printf("\033[0;32mwriter : lock, write begin\033[0m\n");
g_iX = ;
usleep(WRITE_TIME);
pthread_mutex_unlock(&g_Mutex);
printf("\033[0;32mwriter : write ok, unlock\033[0m\n");
}
else
{
printf("\033[0;32mwriter : \033[0;31mbusy , can not write\033[0m\n");
}
usleep(WRITE_TIME);
} return NULL;
} /* reader pthread, read per 20000 us */
void * reader(void * arg)
{
while()
{
if(true == bExit)
{
g_rwok++;
break;
}
if(EBUSY != pthread_mutex_trylock(&g_Mutex))
{
printf("\033[0;33mreader : lock\033[0m\n");
g_iX = ;
usleep(READ_TIME);
pthread_mutex_unlock(&g_Mutex);
printf("\033[0;33mreader : unlock , read ok\033[0m\n");
}
else
{
printf("\033[0;33mreader : \033[0;31mbusy , can not read\033[0m\n");
}
usleep(READ_TIME);
} return NULL;
} int main(int argc, char *argv[])
{
signal(SIGINT, sig);
memset(&g_Mutex, sizeof(g_Mutex), );
pthread_mutex_init(&g_Mutex, NULL); pthread_t preader, pwriter;
pthread_create(&preader, NULL, reader, NULL);
pthread_create(&pwriter, NULL, writer, NULL);
while()
{
if(true == bExit && == g_rwok)
{
break;
}
usleep();
}
pthread_mutex_destroy(&g_Mutex);
printf("\033[0;33mdestroy mutex\033[0m\n"); return ;
}

3、运行结果如下

reader : lock
writer : busy , can not write
reader : unlock , read ok
writer : lock, write begin
reader : busy , can not read
writer : write ok, unlock
reader : lock
reader : unlock , read ok
writer : lock, write begin
reader : busy , can not read
writer : write ok, unlock

linux下使用线程锁互斥访问资源-LMLPHP

04-14 04:06