我有一个创建pthread的main函数。我试图使用信号量在选择性时间打印一个全局变量(注意mutex,s1,s2和memoryUsed全部声明全局):
int main(int argc, const char * argv[])
{
pthread_mutex_init(&mutex, NULL);
sem_init(&s1, 0, 0);
sem_init(&s2, 0, 0);
pthread_t t0;
pthread_create(&t0, NULL, &matrix_management, NULL);
sem_wait(&s1); // wait for signal from pthread
printf("Memory Usage from main: %d bytes\n\n", memoryUsed); // global var
sem_post(&s2); // signal pthread to continue
pthread_join(t0, NULL);
sem_destroy(&s1);
sem_destroy(&s2);
pthread_mutex_destroy(&mutex);
return 0;
}
在我的目标函数中,我想停在选择点并从main打印一个全局变量。注意,变量在目标函数中更改。打印完成后,我想继续使用目标函数:
void *matrix_management(void *len)
{
pthread_mutex_lock(&mutex);
// CHANGE GLOBAL VAR
memoryUsed = 1;
sem_post(&s1); // print from main
sem_wait(&s2); // wait for signal
// continue thread...
pthread_mutex_unlock(&mutex);
return NULL;
}
然而,主线程似乎根本没有等待来自pthread的信号。它立即打印出全局变量的值。如果我在pthread中注释掉信号,程序就不会死锁。你能在MAIN线程和pthread之间使用这样的信号量吗?
答案 0 :(得分:0)
根据您的平台,可能不支持未命名的信号量。在这种情况下,以下内容适用,但您可能希望创建临时名称,稍后将其用于取消链接。我熟悉这个的唯一原因是因为我正常使用的平台OS X不支持通过10.8.3的未命名信号量,因此无错误检查我有类似的行为,因为所有的信号量API失败。
希望它有所帮助。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <assert.h>
sem_t* s1=NULL, *s2=NULL;
int memoryUsed = 0;
void *matrix_management(void *len)
{
// CHANGE GLOBAL VAR
memoryUsed = 1;
sem_post(s1); // print from main
sem_wait(s2); // wait for signal
printf("Thread woken up.\n");
// continue thread...
return NULL;
}
int main(int argc, const char * argv[])
{
s1 = sem_open("s1", O_CREAT, S_IRUSR | S_IWUSR, 0);
s2 = sem_open("s2", O_CREAT, S_IRUSR | S_IWUSR, 0);
assert(s1 && s2 && "Failed to allocate semaphores.");
pthread_t t0;
pthread_create(&t0, NULL, &matrix_management, NULL);
sem_wait(s1); // wait for signal from pthread
printf("Memory Usage from main: %d bytes.\n", memoryUsed); // global var
printf("Waking thread...\n"); // global var
sem_post(s2); // signal pthread to continue
pthread_join(t0, NULL);
printf("Thread finished\n");
sem_close(s1);
sem_close(s2);
sem_unlink("s1");
sem_unlink("s2");
return 0;
}
<强>输出强>
Memory Usage from main: 1 bytes.
Waking thread...
Thread woken up.
Thread finished