我正在尝试实现一个粗略的线程中断。
经常检查“interruptRequested”变量。在操作系统课上,我们学习了饥饿——在这里或类似情况下是否可能?我知道示例程序在运行时的行为符合我的预期,但这可能只是侥幸。
这是我正在做的事情的简化版本:
//Compile with -lpthread
#include <iostream>
#include <signal.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;
bool interruptRequested;
pthread_mutex_t spamMutex;
void *Spam(void *);
int main(int argc, char *argv[])
{
pthread_t tid;
interruptRequested = false;
unsigned long long int timeStarted = time(NULL);
pthread_create(&tid, NULL, Spam, NULL);
unsigned long long int difference = 0;
while (true)
{
pthread_yield();
difference = (time(NULL) - timeStarted);
if ( difference >= 5)//Spam the terminal for 5 seconds
{
//while (pthread_mutex_trylock(&spamMutex));
interruptRequested = true;
//pthread_mutex_unlock(&spamMutex);
break;
}
}
return 0;
}
void *Spam (void *arg)
{
while (true)
{
//while (pthread_mutex_trylock(&spamMutex));
if (interruptRequested == true)
{
//pthread_mutex_unlock(&spamMutex);
break;
}
//pthread_mutex_unlock(&spamMutex);
cout << "I'm an ugly elf" << endl;
pthread_yield();
}
interruptRequested = false;
pthread_exit (0);
}
实际上,在实际代码中我并没有使用时差方法。我的程序将从服务器接收消息,此时我需要中断线程。
最佳答案
如所写,这段代码不一定能保证工作,因为编译器可能会优化工作线程内部对 interruptRequested
的检查,因为它从未在函数内部编写。这意味着生成的代码可能只有一个 while (true)
循环(或类似的东西)。
为防止这种情况发生,您需要以某种方式确保编译器能够识别该变量可能在其他地方被修改。您可以通过标记 interruptRequested
volatile
来做到这一点,它向编译器表明它不应该被优化掉。使用互斥锁也是一个好主意,因为大多数编译器都足够聪明,可以识别出使用互斥锁表明在互斥锁内部引用的变量可能会在外部被修改。
关于c++ - 这部分代码是否需要互斥体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5364597/