我不知道我的信号量和互斥锁无法正常工作的原因


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_STDNT 10
pthread_mutex_t ta;
//sem_t ta; //the ta is the semaphore
//void *request_and_help(void *arg)
//{
//  pthread_t cur_thread = pthread_self();
//
//  if (sem_wait(&ta) == -1) {
//      printf("TA is busy.... student(%d) programming....n");
//  } else {
//      printf("student(%d) requesting help....n", cur_thread);
//      sleep(1);
//      printf("TA is helping student(%d)....n", cur_thread);
//      sleep(1);
//      printf("student(%d) DONE!!!n", cur_thread);
//      sem_post(&ta);  //signal other waiting students to come in
//  }
//}
void *request_and_help(void *arg)
{
pthread_t cur_thread = pthread_self();
if (pthread_mutex_lock(&ta) != 0) {
printf("TA is busy.... student(%d) programming....n");
} else {
printf("student(%d) requesting help....n", cur_thread);
sleep(1);
printf("TA is helping student(%d)....n", cur_thread);
sleep(1);
printf("student(%d) DONE!!!n", cur_thread);
pthread_mutex_unlock(&ta);
}
}
int main(int argc, char *argv[])
{
int i;
pthread_t stdnt[MAX_STDNT];
//sem_init(&ta, 0, 1);
pthread_mutex_init(&ta, NULL);
for (i = 0; i < MAX_STDNT; i++)
pthread_create(&stdnt[i], NULL, request_and_help, NULL);
for (i = 0; i < MAX_STDNT; i++)
pthread_join(stdnt[i], NULL);
}

我编写这段代码的目的是了解线程应用程序编程的POSIXAPIS是如何工作的。

以下是它的工作原理,ta充当信号量(或互斥),学生们将获得帮助一次一个。如果TA忙(这意味着线程获得了锁),它会打印"忙",等待的线程被描述为"编程"。事实是,如果我编译并执行这个程序,就根本没有等待消息。

不幸的是,至少有一个线程必须获得信号量资源(或互斥量),它将在1秒内休眠2次,这意味着其他线程(显然可能已经进入了while)必须等待信号量资源或互斥量,我通过打印"TA正忙学生正在编程"来检查该信号量资源。

但当我执行程序时,我看不到任何消息。对于这段代码,我有两个版本的信号量和互斥量,我发布的一个版本是当前正在使用互斥。有人能帮我吗?

p.S我的环境是windows上的cygwin,使用多线程处理器上网本

如果在已锁定的互斥体上调用pthread_mutex_lock(),它会阻止有关互斥体解锁。

为了实现您想要的行为,您可能希望像这样使用pthread_mutex_trylock()

void * request_and_help(void * arg)
{
pthread_t cur_thread = pthread_self();
int result = pthread_mutex_trylock(&ta);
if (0 != result)
{
if (EBUSY == result) 
{
printf("TA is busy.... student(%d) programming....n", cur_thread);
}
else
{
errno = result;
perror("pthread_mutex_trylock() failed");
}
} 
else 
{
[...]

最新更新