#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);
}
我对这段代码的意图是了解线程应用程序编程的POSIX APIS是如何工作的 .
这是它的工作原理,ta作为信号量(或互斥量),学生将一次获得一个帮助 . 如果TA忙(这意味着线程获得锁定,它打印“忙”,等待线程被描述为“编程” . 事实上,如果我编译这个程序并执行它,就没有等待消息 .
至少有一个线程必须获得信号量资源(或互斥量)并且它将在1秒内休眠2次,这意味着其他线程(显然可能已进入其中)必须等待我检查过的sempahore资源(或互斥)打印“TA正忙着学生正在编程” .
但是当我执行程序时,我没有看到任何消息 . 我有两个版本的信号量和互斥量,每个用于此代码,我发布的一个版本目前正在使用互斥锁 . 有谁能够帮我?
P.S我的环境是windows上的cygwin和使用多线程处理器上网本
1 回答
如果在已锁定的互斥锁上调用pthread_mutex_lock(),则会阻止有问题的互斥锁已解锁 .
要实现您想要的行为,您可能希望像这样使用pthread_mutex_trylock():