作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 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 核处理器,那么我可以使用哪个函数来暂停主线程的子线程?
我已经咨询过How to make main thread wait for all child threads finish?但这并没有完全帮助我。
最佳答案
因此,如果您想暂停主线程直到子线程发出信号结束,您可以使用互斥锁来锁定主线程:
#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 */
}
关于c - 如何让子线程等待主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840185/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!