【发布时间】:2019-05-25 20:14:36
【问题描述】:
我有这个来自官方 geeks4geeks 网站的程序,它在 2 个线程之间使用信号量:
// C program to demonstrate working of Semaphores
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t mutex;
void* thread(void* arg)
{
//wait
sem_wait(&mutex);
printf("\nEntered..\n");
//critical section
sleep(4);
//signal
printf("\nJust Exiting...\n");
sem_post(&mutex);
}
int main()
{
sem_init(&mutex, 0, 1);
pthread_t t1,t2;
pthread_create(&t1,NULL,thread,NULL);
sleep(2);
pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
sem_destroy(&mutex);
return 0;
}
根据这个站点运行它会打印这个结果:
Entered..
Just Exiting...
Entered..
Just Exiting...
在我的 ubuntu linux 计算机中,我使用 gcc main.c -lpthread -lrt 编译它,它编译成功,但之后尝试使用 ./main.c 运行它会给我以下错误:
./main.c: line 8: sem_t: command not found
./main.c: line 10: syntax error near unexpected token `('
./main.c: line 10: `void* thread(void* arg)'
我应该用不同的命令运行它还是我在这里遗漏了什么?请帮忙。
【问题讨论】:
标签: c operating-system