多线程并行与退出

本文探讨了多线程并行处理的概念,并通过两个实例——进程与线程并行输出及线程等待与退出函数的使用,详细解释了如何在实际编程中实现线程的高效协作与安全退出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例1:进程与线程并行输出


#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>

//线程函数入口
void *thread_routine(void *arg)
{
	printf("I am a thread, my thread id is : %d\n", pthread_self());
        int i;
	for ( i = 0; i < 5; i++)
	{
		printf("thread i = %d\n", i);
		fflush(stdout); //冲洗缓冲区,避免影响进程
		sleep(1);
	}
	printf("I am a thread, I will exit\n");

}

int main()
{
	pthread_t tid;
	int ret = 0;
	ret = pthread_create(&tid, NULL, thread_routine, NULL); //创建一个线程
	if (ret != 0)
	{
		printf("pthread_create error\n");
		exit(0);
	}
        int i;
	for ( i = 0; i < 5; i++)
	{
		printf("main i = %d\n", i);
		fflush(stdout); //冲洗缓冲区,避免影响线程
		sleep(1);
	}
	sleep(2); //等待线程退出,如果线程还在执行,但是进程退出,那么线程也会退出
	printf("parent exit\n");
	exit(0);
	

}


例2:等待线程与线程退出函数

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>

//线程函数入口
void *thread_routine(void *arg)
{
	printf("I am a thread, my thread id is : %d\n", pthread_self());
	int i;
	for (i = 0; i < 5; i++)
	{
		printf("thread i = %d\n", i);
		fflush(stdout); //冲洗缓冲区,避免影响进程
		sleep(1);
	}
	sleep(3);
	printf("child exit\n");
	pthread_exit(NULL);//线程结束函数

}

int main()
{
	pthread_t tid;
	int ret = 0;
	ret = pthread_create(&tid, NULL, thread_routine, NULL); //创建一个线程
	if (ret != 0)
	{
		printf("pthread_create error\n");
		exit(0);
	}
	int i;
	for (i = 0; i < 5; i++)
	{
		printf("main i = %d\n", i);
		fflush(stdout); //冲洗缓冲区,避免影响线程
		sleep(1);
	}
	pthread_join(tid, NULL);//等待线程退出
	printf("parent exit\n");
	exit(0);


}

例3:创建多个线程,并向线程传递数据

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>

typedef struct Threadinfo
{
	char name[64];
	int age;
	int numId;

}ThreadInfo;

int nNum, nLoop;
void *thread_routine(void *arg)
{
	int i = 0;
	ThreadInfo * p = (ThreadInfo*)arg;
	for (i = 0; i < nLoop; ++i)
	{
		printf("thread id is : %d, numid is %d\n", pthread_self(), i, p->numId);

	}
	printf("child exit: %d\n", pthread_self());
	pthread_exit(arg);
}

int main()
{
	int i = 0;
	pthread_t tidArray[200];
	ThreadInfo tmp[200];

	printf("Input the number of thread:");
	scanf("%d", &nNum);
	printf("Input the number of nLoop:");
	scanf("%d", &nLoop);

	int ret = 0;
	for (i = 0; i < nNum; ++i)
	{
		memset(&tmp[i], 0, sizeof(ThreadInfo));
		tmp[i].numId = i;
		pthread_create(&tidArray[i], NULL, thread_routine, &tmp[i]);
	}

	for (i = 0; i < nNum; ++i)
	{
		pthread_join(tidArray[i], NULL);
	}
	printf("parent exit\n");
	exit(0);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值