您的位置:首页 > 运维架构 > Linux

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

2016-05-18 13:49 519 查看
#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) 外面,容易导致死锁;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息