多线程 + 互斥锁 + 条件变量

119 阅读1分钟
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>

static char g_buf[1000];
static pthread_mutex_t g_tMutex  = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  g_tConVar = PTHREAD_COND_INITIALIZER;

/**
* 打包:gcc -o thread5 ./thread5.c -lpthread
* 多线程 + 互斥锁 + 条件变量
* 编译: gcc -o thread4 ./thread.c -lpthread
*/

static void *my_thread_func (void *data)
{
	while (1)
	{
		printf("1111\n");
		/** 互斥锁 */
		pthread_mutex_lock(&g_tMutex);
		printf("2222\n");
		/* 等待通知 */
		pthread_cond_wait(&g_tConVar, &g_tMutex);
		printf("3333\n");	
		/* 打印 */
		printf("recv: %s\n", g_buf);
		pthread_mutex_unlock(&g_tMutex);
	}

	return NULL;
}


int main(int argc, char **argv)
{
	pthread_t tid;
	int ret;
	char buf[1000];
	
	/* 1. 创建"接收线程" */
	ret = pthread_create(&tid, NULL, my_thread_func, NULL);
	if (ret)
	{
		printf("pthread_create err!\n");
		return -1;
	}


	/* 2. 主线程读取标准输入, 发给"接收线程" */
	while (1)
	{
		fgets(buf, 1000, stdin);
		printf("44444\n");	
		pthread_mutex_lock(&g_tMutex);
		printf("55555\n");	
		memcpy(g_buf, buf, 1000);
		printf("666666\n");	
		pthread_mutex_unlock(&g_tMutex);
		printf("77777\n");	

        pthread_cond_signal(&g_tConVar); /* 通知接收线程 */
		printf("8888\n");	
	}
	return 0;
}