所以我一直在尝试将多线程实现到我的程序中(对于macOS)但是我遇到了一些问题,第一个是当我尝试退出主线程赢得的线程时。继续运行,我的第二个问题是我创建的每个线程我的CPU使用率上升了~100%,这是我降低CPU使用率的最佳方式吗?
干杯
void *KeepListening(void *commandid) {
long tid = (long)commandid;
if(tid != 1)
return 0;
for(int i = 0; killthread == false ; i++) {
if(i % WhenToSleep == 1)
sleep(10);
if(i % waittime == 1) {
abc = con->post(listento, "request=abc");
xyz = con->post(listento, "request=xyz");
sleep(1);
if(abc == "true") {
threadscreated = false;
} else if(abc == "false") {
killthread = true;
}
}
}
cout << "Killing thread\n";
shouldcreate = true;
pthread_exit(NULL);
}
void Listen() {
pthread_t threads[1];
int rc;
for(int i = 0; ;i++) {
if(i % WhenToSleep == 1)
sleep(10);
if(i % waittime == 1) {
abc = con->post(listento, "request=abc");
xyz = con->post(listento, "request=xyz");
sleep(1);
if(abc == "true") {
threadscreated = false;
} else if(abc == "false") {
killthread = true;
}
}
if(!threadscreated && shouldcreate) {
rc = pthread_create(&threads[0], NULL, HandleCommands, (void *)1);
sleep(1);
threadscreated = true;
shouldcreate = false;
cout << "Threads Created\n";
sleep(5);
}
}
pthread_exit(NULL);
}