天天看點

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) 外面,容易導緻死鎖;

繼續閱讀