【发布时间】:2021-02-25 03:37:33
【问题描述】:
以下代码是用 C 编写的,当我运行代码时,没有任何输出到屏幕上。我没有在 IDE 中编码,所以我无法确定错误的位置。请,任何帮助表示赞赏。
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
int counter=0;//this is the count variable and is the variable that the treads will edit, making it the critical section
static sem_t semaphore;//this creates a pointer for our semaphore variable
void *increaseCounter();
void *decreaseCounter();
int main()
{
sem_init(&semaphore, 0, 1);
pthread_t t1,t2;
pthread_create(&t1, NULL, increaseCounter, NULL);
pthread_create(&t2, NULL, decreaseCounter, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&semaphore);
}
void *increaseCounter()
{
while(1)
{
sem_wait(&semaphore);
counter++;
printf("\n%d\n",counter);
sem_post(&semaphore);
}
}
void *decreaseCounter()
{
while(1)
{
sem_wait(&semaphore);
counter--;
printf("\n%d\n",counter);
sem_post(&semaphore);
}
}
【问题讨论】:
-
检查
pthread_create的返回值来验证线程是否被正确创建。此外,线程处理函数应定义为采用void *参数。最后,执行基本调试,例如在线程函数的开头放置一条打印语句,以查看线程是否运行。 -
一个主要问题是
semaphore是一个空指针。而是应该声明为static sem_t semahpore;并作为sem_init(&semaphore, 0, 1);传入 -
@kaylum 我解决了这个问题,但仍然没有收到任何输出
-
修复了什么?您是否按照建议进行了基本调试?你检查
pthread_create的返回值了吗? -
@kaylum,我还尝试在每个线程创建之后和信号量创建之后放置打印语句,看起来它甚至从未运行过 main() 方法。即使第一个语句是打印语句,也没有任何输出
标签: c terminal output pthreads semaphore