问题:
我正在开发一个 C 程序,其中有两个线程 p1 和 p2,我需要它们打印序列 1234 1234 1234 ....我正在使用信号量来同步线程,但输出不符合预期.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t s1, s2;
void *p1(void *arg) {
while (1) {
printf("1");
sem_post(&s1);
sem_wait(&s2);
printf("3");
sem_post(&s1);
}
return NULL;
}
void *p2(void *arg) {
while (1) {
sem_wait(&s1);
printf("2");
sem_post(&s2);
sem_wait(&s1);
printf("4 ");
}
return NULL;
}
int main() {
sem_init(&s1, 0, 0);
sem_init(&s2, 0, 0);
pthread_t t1, t2;
pthread_create(&t1, NULL, p1, NULL);
pthread_create(&t2, NULL, p2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&s1);
sem_destroy(&s2);
return 0;
}
输出是:12314 2314 2314 ...而不是预期的1234 1234 1234 ....有人可以帮我修复信号量同步以获得正确的输出吗?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t s1, s2;
void *p1(void *arg) {
(void)arg; // Silence "unused" warning.
for (int i=10; i--; ) {
sem_wait(&s2); // This was missing.
printf("1");
sem_post(&s1);
sem_wait(&s2);
printf("3");
sem_post(&s1);
}
return NULL;
}
void *p2(void *arg) {
(void)arg; // Silence "unused" warning.
for (int i=10; i--; ) {
sem_wait(&s1);
printf("2");
sem_post(&s2);
sem_wait(&s1);
printf("4 ");
sem_post(&s2); // This was missing.
}
return NULL;
}
int main(void) {
sem_init(&s1, 0, 0);
sem_init(&s2, 0, 1); // This wasn't initialized correctly.
pthread_t t1, t2;
pthread_create(&t1, NULL, p1, NULL);
pthread_create(&t2, NULL, p2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&s1);
sem_destroy(&s2);
return 0;
}
编译器资源管理器上的