c - 在等待输入时每秒将输出消息循环到标准输出 - PTHREAD
问题描述
我正在使用线程。我有一个线程每 a1 秒输出到标准输出“等待......”。我试图在我的主线程中的标准输入中写入一些东西,但是当“等待......”输出发生时,它会吸收我到目前为止能够写的字母。我真的很困惑。我假设我只需要在标准输入中检测到换行符时才需要输出,但我不知道如何检查它。
它为我提供的输出:
waiting ...
waiting ...
fri <-- me trying to input friends
friwaiting ... <-- fri gets sucked in halfway through me typing it
waiting ...
waiting ...
我的代码:
void* thread_one(void* arg){
while(1){
sleep(1);
if (write(1, "waiting ...\n", 12) != 12) {
write(2, "There was an error writing to standard out\n", 44);
}
}
return NULL;
}
int main(int argc, char **argv){
char buffer[11];
pthread_t tid;
pthread_create(&tid, NULL, thread_one, NULL);
while(1){
int r = read(0, buffer, 10);
if(r<=0){
break;
}
buffer[r] = 0;
printf("message: %s\n", buffer);
if(strcmp(buffer, "exit\n")==0){
break;
}
}
return 0;
}
非常感谢正确方向的任何一点。先感谢您!
解决方案
在您的情况下,您必须同步两个线程的读写。在这种情况下,最简单的方法是使用mutex
. 你可以看到下面的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
// using the mutex "lock"
pthread_mutex_t lock;
void* thread_one(void* arg){
while(1){
sleep(1);
// lock the mutex
pthread_mutex_lock(&lock);
if (write(1, "waiting ...\n", 12) != 12) {
write(2, "There was an error writing to standard out\n", 44);
}
// unlock the mutex after writing
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(int argc, char **argv){
char buffer[11];
pthread_t tid;
pthread_mutex_init(&lock], NULL);
pthread_create(&tid, NULL, thread_one, NULL);
while(1){
// lock mutex to read
pthread_mutex_lock(&lock);
int r = read(0, buffer, 10);
// unlock after reading
pthread_mutex_unlock(&lock);
if(r<=0){
break;
}
buffer[r] = 0;
printf("message: %s\n", buffer);
if(strcmp(buffer, "exit\n")==0){
break;
}
}
return 0;
}
输出:
waiting ...
message: friday
monday
message: monday
waiting ...
您也可以在本教程pthread中获得一些知识
推荐阅读
- unity3d - Unity:NullReferenceException:对象引用未设置为具有多个 gameObject.SetActive 语句的对象实例
- ssh - vagrant ssh 调用的是 22 而不是 2222?- 权限被拒绝(公钥)
- google-cloud-platform - 无法在 GCP 中创建新项目,位置权限问题
- r - 计算 R 数据中的更新频率
- python - django.db.utils.OperationalError 的解决方案
- mongodb - 如何查找mongo DB查询慢的原因?
- grafana - 我应该使用什么查询向 grafana 显示状态代码?
- sql-server - 由于缺少权限,SQL Server 服务无法启动
- angular - 如何在 Angular 中搜索两个文档而不是两个文档时发出一个服务请求?
- javascript - 动态具有多个 colspan 的表格单元格