C语言信号量实现两线程循环打印


#include <stdio.h>
#include <pthread.h>
#include <error.h>
#include <sys/types.h>
#include <semaphore.h>
#include <stdlib.h>
sem_t sem1,sem2;
int number[10]={1,2,3,4,5,6,7,8,9,10}; 
int i=0;

void thread1(void)
{
	do
	{
		sem_wait(&sem1);//等待sem1信号量
		printf("thread1--->number[%d]=%d\n",i,number[i]);
		i++;
		sem_post(&sem2);//增加sem2信号量,使得thread2能够执行
	}while(i<=9);
	pthread_exit(NULL);
}
void thread2(void)
{
	do
	{
		sem_wait(&sem2);
		printf("thread2--->number[%d]=%d\n",i,number[i]);
		i++;
		sem_post(&sem1);
	}while(i<=9);
	pthread_exit(NULL);
}

int main()
{
	int ret;
	pthread_t a,b;
	sem_init(&sem1,0,1);//初始化sem1为1,使thread1先执行
	sem_init(&sem2,0,0);
	ret=pthread_create(&a,NULL,(void *)thread1,NULL);
	if(ret!=0)
	{
		printf ("Create pthread error!\n");
		exit (1);
	}
	ret=pthread_create(&b,NULL,(void *)thread2,NULL);//返回值为0,创建成功
	if(ret!=0)
	{
		printf ("Create pthread error!\n");
		exit (1);
	}
	pthread_join(a,NULL);
	pthread_join(b,NULL);
	sem_destroy(&sem1);
	sem_destroy(&sem2);
	return 0;
}


  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一种可能的解决方案: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #define NUM_THREADS 3 #define NUM_LOOPS 10 sem_t semaphores[NUM_THREADS]; void* thread_func(void* arg) { int id = *(int*)arg; for (int i = 0; i < NUM_LOOPS; i++) { sem_wait(&semaphores[id]); printf("Thread %d: %d\n", id, i); sem_post(&semaphores[(id + 1) % NUM_THREADS]); } pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int thread_ids[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { sem_init(&semaphores[i], 0, 0); thread_ids[i] = i; pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]); } sem_post(&semaphores[0]); for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); sem_destroy(&semaphores[i]); } return 0; } ``` 该程序首先定义了三个信号量,每个线程一个。然后创建三个线程,每个线程都调用`thread_func`函数。`thread_func`函数首先接受线程ID作为参数,然后使用一个循环来输出数字并交替地等待和释放信号量。每个线程都等待其对应的信号量,输出数字后释放下一个线程信号量,以此类推,实现交替输出。最后,主线程等待所有线程完成并销毁信号量。 注意,信号量的初始值为0,因此第一个线程需要在开始时手动释放它的信号量。在这个例子中,我们使用了一个简单的数组来保存线程ID,但实际上可能需要更复杂的数据结构来跟踪线程之间的依赖关系。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值