C语言 我希望使用一个信号量值输出为 1 2 3 4.如何实现这一点?



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

#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
sem_t sem;
void *thread1(void *argv)
{
printf("1t");
sem_wait(&sem);
printf("3t");
pthread_exit(NULL);
}
void *thread2(void *argv)
{
//    sem_post(&sem);
sem_post(&sem);
printf("2t");
sem_wait(&sem);
printf("4t");
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 用于一次有效地强制一个线程,"next"控制哪个线程必须实际执行下一个任务。

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

一旦分叉,e ach线程,将检查是否轮到他执行(i = =下一个(

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

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

#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("%dn", 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("%dn", 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

相关内容

最新更新