我正在嘗試執行粗線程中斷。這部分代碼是否需要互斥鎖?
'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