简单实现两个线程之间的交替打印(C语言)

#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <signal.h>

pthread_mutex_t mutex;//自旋锁
pthread_cond_t cond1,cond2;
//线程1
void *thread_fun1(void * arg)
{
	int i=0;
	while(1)
	{
		pthread_mutex_lock(&mutex);//加锁
		printf("a\n");
		pthread_cond_signal(&cond2);//唤醒另一个
		pthread_cond_wait(&cond1,&mutex);//等待被唤醒
		pthread_mutex_unlock(&mutex);//解锁
		sleep(1);
		
	}
	return NULL;
}

void *thread_fun2(void * arg)
{
	int i=1;
	while(1){
		pthread_mutex_lock(&mutex);//加锁
		sleep(1);
		printf("b\n");
		pthread_cond_signal(&cond1);//唤醒另一个
		pthread_cond_wait(&cond2,&mutex);//等待被唤醒
		pthread_mutex_unlock(&mutex);//解锁
	}
	return NULL;
} 

int main()
{
	
	//创建线程
	
	pthread_t pth1,pth2;
	pthread_create(&pth1,NULL,thread_fun1,NULL);
	pthread_create(&pth2,NULL,thread_fun2,NULL);
	
	//回收线程和自旋锁
	pthread_join(pth1,NULL);
	pthread_join(pth2,NULL);
	pthread_mutex_destroy(&mutex);
	while(1);
	return 0;
}

效果如下:

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Linux 中,可以使用 pthread 库来实现线程。下面是一个简单的示例代码,用于创建两个线程并执行: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *thread_func(void *arg) { int i; for (i = 0; i < 5; i++) { printf("Thread %d is running.\n", *((int *) arg)); sleep(1); } return NULL; } int main() { pthread_t tid1, tid2; int ret1, ret2; int id1 = 1, id2 = 2; ret1 = pthread_create(&tid1, NULL, thread_func, &id1); if (ret1 != 0) { printf("Error creating thread 1.\n"); exit(EXIT_FAILURE); } ret2 = pthread_create(&tid2, NULL, thread_func, &id2); if (ret2 != 0) { printf("Error creating thread 2.\n"); exit(EXIT_FAILURE); } pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; } ``` 在这个示例中,我们首先定义了一个线程函数 `thread_func`,它接受一个 `void *` 类型的参数 `arg`,我们将一个整数地址传递给它。在这个函数中,我们使用一个循环打印线程的 id,并且让线程睡眠 1 秒钟。最后,我们让线程返回 `NULL`。 在 `main` 函数中,我们首先定义了两个线程 id `tid1` 和 `tid2`,以及两个整数 `id1` 和 `id2`。然后,我们使用 `pthread_create` 函数创建两个线程,分别传递线程函数和对应的整数地址作为参数。如果创建线程出错,我们将会打印出错误信息并退出程序。最后,我们使用 `pthread_join` 函数等待线程结束,并释放线程资源。 当我们运行这个程序时,我们将会看到以下输出: ``` Thread 1 is running. Thread 2 is running. Thread 1 is running. Thread 2 is running. Thread 1 is running. Thread 2 is running. Thread 1 is running. Thread 2 is running. Thread 1 is running. Thread 2 is running. ``` 这表明两个线程交替运行,并且每个线程运行 5 次。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值