我正在尝试执行粗线程中断。这部分代码是否需要互斥锁?
'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);
}
其实,在真正的代码,我不使用的时间差的方式。我的程序将从服务器收到一条消息,此时我需要中断该线程。
+1是的,使用volatile属性是一个好主意 – fabrizioM 2011-03-19 20:16:09