【发布时间】:2020-04-17 11:20:43
【问题描述】:
所以我有这个代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <semaphore.h>
#define nr_threads 3
sem_t semaphores[nr_threads];
typedef struct {
int id;
char *word;
}th_struct;
void *thread_function(void *arg)
{
th_struct *th_data = (th_struct *) arg;
sem_wait(&semaphores[th_data->id]);
printf("[thread#%d] %s\n", th_data->id, th_data->word);
sem_post(&semaphores[th_data->id + 1]);
return NULL;
}
int main(int argc, char **argv)
{
pthread_t tid[nr_threads];
th_struct th_data[nr_threads];
for(int i = 0; i < nr_threads; i++){
if (sem_init(&semaphores[i], 0, 1) != 0){
perror("Could not init semaphore");
return -1;
}
}
sem_post(&semaphores[0]);
for(int i = 0; i < nr_threads; i++){
th_data[i].id = i;
th_data[i].word = argv[i + 1];
pthread_create(&tid[i], NULL, thread_function, &th_data[i]);
}
for(int i = 0; i < nr_threads; i++){
pthread_join(tid[i], NULL);
}
for(int i = 0; i < nr_threads; i++)
sem_destroy(&semaphores[i]);
return 0;
}
我从命令行给出三个单词,例如“一二三”,每个线程打印一个单词,同步,这样顺序总是正确的。
我是线程和信号量的新手,我的大脑目前习惯于 sem_wait(sem) 和 sem_post(sem) 之后,其中 sem 是同一个信号量。我要问的是对这段代码为什么工作以及它是如何工作的完整解释。为什么用 0 权限初始化信号量?为什么会有 sem_post(first_semaphore)?我很困惑。
【问题讨论】:
标签: c linux multithreading synchronization