天天看点

linux C 多线程获取字符输入方法

#define READ_BUF_LEN                8

pthread_t lTestThread;


static void *doTestThreadFunc(void *parg)
{
	char acBuf[READ_BUF_LEN];
	char cCounti;
	int nTestData;

	while(1)
	{
		memset(acBuf, 0, READ_BUF_LEN);
		printf("input:");

		fgets(acBuf, READ_BUF_LEN, stdin);
		for(cCounti=0; cCounti<READ_BUF_LEN; cCounti++)
		{
			if(acBuf[cCounti] == '\n')
			{
				acBuf[cCounti] = '\0';
				break;
			}
		}

		printf("-- %s --\n", acBuf);
		nTestData = strtol(acBuf, NULL, 0);
		printf("0x%x \n", nTestData);

		startSettingFunc(nTestData);
	}

	pthread_exit(NULL);
}
           

容易出错的地方:

1)必须明确使用 fgets 的长度,谨慎使用 strlen() 函数,当没有输入时,strlen() 获取到的长度就为 0,是错的;

2)线程互斥锁只能锁临界资源,不能锁再线程 while(1) 外面,容易导致死锁;

继续阅读