gpt4 book ai didi

c - 我希望使用一个信号量值输出为 1 2 3 4。如何实现这一目标?

转载 作者:行者123 更新时间:2023-11-30 19:25:19 25 4
gpt4 key购买 nike

我想使用此代码打印 1 2 3 4,并且仅使用一个信号量,任何人都可以告诉我如何做到这一点,并且我尝试了一种未打印所需结果的方法。

#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
sem_t sem;
void *thread1(void *argv)
{
printf("1\t");
sem_wait(&sem);
printf("3\t");
pthread_exit(NULL);
}
void *thread2(void *argv)
{
// sem_post(&sem);
sem_post(&sem);
printf("2\t");
sem_wait(&sem);
printf("4\t");

pthread_exit(NULL);
}
int main(void)
{
sem_init(&sem,0,0);
pthread_t p1, p2;
pthread_create(&p1,NULL,thread1,NULL);
pthread_create(&p2,NULL,thread2,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
return 0;
}

最佳答案

如果两个线程之间没有共享额外的状态,就不可能保证交替执行。您可以使用全局变量实现额外的状态。

在下面的示例中,sem 用于有效地强制一次一个线程,“下一个”控制哪个线程必须实际执行下一个任务。

为了概括并改进测试,范围扩展到 1 到 9(而不是 1 到 4)。可以通过调整循环来缩小规模。

一旦 fork ,e每个线程都会检查是否轮到他执行(i==next)

  • 如果是,它将在信号量锁定的情况下:执行他的作业(打印下一个整数),并设置下一个以指示下一站应该运行
  • 如果没有轮到他,它将释放锁,然后重试。

即使一个线程需要重复锁定/解锁,在某个时间点,系统也会允许备用线程锁定信号量并完成其工作。

#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
sem_t sem;
static volatile int next ;
void *thread1(void *argv)
{
for (int i=1 ; i<10 ; i+=2 ) {
// Spinlock like loop
while ( 1 ) {
sem_wait(&sem) ;
if ( i == next ) break ;
sem_post(&sem) ;
} ;
// Semaphore still locked
printf("%d\n", i) ;
next++ ;
sem_post(&sem) ;
}
}
void *thread2(void *argv)
{
for (int i=2 ; i<10 ; i+=2 ) {
// Spinlock like loop
while ( 1 ) {
sem_wait(&sem) ;
if ( i == next ) break ;
sem_post(&sem) ;
} ;
// Semaphore still locked
printf("%d\n", i) ;
next++ ;
sem_post(&sem) ;
} ;
}
int main(void)
{
sem_init(&sem,0,0);
pthread_t p1, p2;
pthread_create(&p1,NULL,thread1,NULL);
pthread_create(&p2,NULL,thread2,NULL);
next = 1 ;
sem_post(&sem) ;
pthread_join(p1,NULL);
pthread_join(p2,NULL);
return 0;
}

受到类似主题的 Java 文章的启发:https://www.baeldung.com/java-even-odd-numbers-with-2-threads

关于c - 我希望使用一个信号量值输出为 1 2 3 4。如何实现这一目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com