c - 如何让子线程等待主线程
问题描述
我有 2 个线程:一个检测鼠标事件的子线程,另一个执行程序的主线程。
全局变量:
int g_wait = 0;
子线程:
void *mouseEvent2(void *arg)
{
int fd;
struct input_event ev;
const char* pFile = "/dev/input/event0";
signal(SIGINT, SAMPLE_VGS_HandleSig);
signal(SIGTERM, SAMPLE_VGS_HandleSig);
fd = open(pFile, O_RDONLY);
if (fd == -1) {
printf("ERROR Opening %s\n", pFile);
return NULL;
}
while(scroll != -1) {
read(fd, &ev, sizeof(ev));
[... Some code with if statement ... ]
if(...) //left mouse button
g_wait = !g_wait;
[need waiting so the thread won't use at 100% a core]
}
close(fd);
(void) arg;
pthread_exit(NULL);
}
主线程:
int main() {
[... some code and initilisation here ...]
if(pthread_create(&scrollThread, NULL, mouseEvent2, NULL))
goto _FAILURE_;
do {
[...]
while(g_wait);
}
[... some deinit ...]
_FAILURE_ :
pthread_join(scrollThread, NULL);
[... some other deinit ...]
return 0;
}
我的问题是:当我的主线程等待时,我的子线程正在 100% 使用 1 个核心处理器,那么我可以使用哪个函数来暂停主线程的子线程?
我已经咨询了如何让主线程等待所有子线程完成?但这并没有完全帮助我。
解决方案
所以,如果你想暂停主线程,直到子线程发出信号结束,你可以使用互斥锁来锁定主线程:
#include "stdio.h"
#include "pthread.h"
/* I work on windows now, so i need windows sleep function to test example */
/* platform independed sleep function */
#ifdef _WIN32
# include "windows.h"
# define platform_sleep(ms) Sleep(ms)
#else
# include "unistd.h"
# define platform_sleep(s) sleep(s / 1000)
#endif
pthread_mutex_t mtx;
void *
child_func(void *arg)
{
/* simulate some hard work */
platform_sleep(3000); /* 3 secs */
/* after this "hard work" we allow main thread to continue */
pthread_mutex_unlock(&mtx);
}
int
main()
{
pthread_mutex_init(&mtx, NULL);
pthread_mutex_lock(&mtx);
pthread_t child;
pthread_create(&child, NULL, child_func, NULL);
/* mutex is already locked by main thread, so it waits */
/* until child thread unlock it */
pthread_mutex_lock(&mtx);
pthread_mutex_destroy(&mtx);
/* do work after child ends */
}
推荐阅读
- node.js - 无法将另一个集合中的对象插入到表单提交时创建的新文档
- laravel - Laravel - 如何更新动态输入字段
- 8thwall-xr - 如何在 Mac 中为 8thwall web ar 编写代码并进行测试?
- python - 如何使用不同的功能来替换列表中的项目?
- c# - 在子视图 XAML 中使用来自父视图的命令
- node.js - Nodejs 是否有任何支持创建 winform 的框架/库?
- python - 需要使用另一个 csv 的值更新一个 csv 中的特定列,但整行会更新
- python - pyttsx3 模块在运行时抛出错误
- python - 如何使用拆分函数从列值创建多列
- kubernetes - 如何检查 Kubernetes 集群中现有的用户和组?