⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 key1.c

📁 gcc 下pthread 使用
💻 C
字号:
#include <stdio.h>
#include <pthread.h>

typedef struct thddata_t
{
	volatile int exit_code;
	pthread_t thdid;
	pthread_attr_t attr;

	pthread_mutex_t mutex;
	pthread_cond_t cond;
	int key;

}thddata_t;
static thddata_t thddata;

void* thread_proc(void* idp)
{
	//open the key file and get the file descriptor
	int retval = 0;

	int fd = 0;
	fd_set rfds;
	FD_ZERO(&rfds);
	FD_SET(fd, &rfds);

	thddata.exit_code = 1;

	while(thddata.exit_code)
	{
		retval = select(fd + 1, &rfds, NULL, NULL, NULL);
		if(retval)
		{
			pthread_mutex_lock(&thddata.mutex);

			thddata.key = getchar();
			if(thddata.key == 10)
				continue;
			printf("thread_proc: key = %c, %d\n", thddata.key, thddata.key);
			pthread_cond_signal(&thddata.cond);
			
			pthread_mutex_unlock(&thddata.mutex);
			
			if((thddata.key == 'q') || (thddata.key == 'Q'))
				break;
		}
		else
			printf("no data.\n");
	}

	printf("thread_proc exit.\n");
	pthread_exit(NULL);
}


int main()
{
	int key = 0;

	pthread_mutex_init(&thddata.mutex, NULL);
	pthread_cond_init (&thddata.cond, NULL);
	pthread_attr_init(&thddata.attr);
	pthread_attr_setdetachstate(&thddata.attr, PTHREAD_CREATE_JOINABLE);
	
	pthread_create(&thddata.thdid, &thddata.attr, thread_proc, NULL);

	while(1)
	{
		pthread_mutex_lock(&thddata.mutex);

		pthread_cond_wait(&thddata.cond, &thddata.mutex);
		key = thddata.key;
		if((key == 'q') || (key == 'Q'))
			break;
		printf("main: key = %c, %d\n", thddata.key, thddata.key);
		
		pthread_mutex_unlock(&thddata.mutex);				
	}


	pthread_join(thddata.thdid, NULL);

	pthread_attr_destroy(&thddata.attr);
	pthread_cond_destroy(&thddata.cond);
	pthread_mutex_destroy(&thddata.mutex);

	printf("main exit.\n");
	pthread_exit(NULL);

	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -