【发布时间】:2021-07-07 10:20:57
【问题描述】:
我有新数据出现在公共汽车上。我希望我的主线程在新数据到达时“唤醒”。我原来的代码是这样的:
#include <time.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
int data = 0;
void* thread_func(void* args)
{
while(1)
{
sleep(2);
data = random() % 5;
}
return NULL;
}
int main()
{
int tid;
pthread_create(&tid, NULL, &thread_func, NULL);
while(1)
{
// Check data.
printf("New data arrived: %d.\n", data);
sleep(2);
}
return 0;
}
但显然主线程中的无限 while 循环是多余的。所以我想这个怎么样?
#include <time.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
int data = 0;
pthread_mutex_t mtx;
void* thread_func(void* args)
{
while(1)
{
sleep(2);
// Data has appeared and can be read by main().
data = random() % 5;
pthread_mutex_unlock(&mtx);
}
return NULL;
}
int main()
{
int tid;
pthread_mutex_init(&mtx, NULL);
pthread_create(&tid, NULL, &thread_func, NULL);
while(1)
{
pthread_mutex_lock(&mtx);
printf("New data has arrived: %d.\n", data);
}
return 0;
}
这可行,但这是最好的方法吗?
实际上,我不仅有一个主线程,还有几个线程,我希望它们处于休眠状态,直到它们的新数据到达。这将涉及为每个线程使用一个互斥锁。这是最好的做事方式吗?
我希望它很清楚。谢谢。
【问题讨论】:
-
C 或 C++?这些是完全不同的语言。这看起来像是 100% 的 C 代码。
-
与语言无关的关键字是 message queue。
-
查找“信号量”。
-
嗨,为了简单起见,我编写了 C 代码,除非 C++ 提供有用的工具,否则我宁愿坚持下去。
-
你锁定一个线程,但解锁另一个线程?...
标签: c linux multithreading mutex