pthread线程

pthread是linux下面遵循posix标准的多线程接口,该线程测试,就类似于RTOS的任务测试是一样的,接下来主要测试了其中的两个函数pthread_create线程创建和pthread_join等待线程结束

  如果主线程中不调用pthread_join等待创建的线程结束,那么有可能会出现主线程已经结束导致整个进程退出,然而被创建的线程还未运行或者还未运行完毕,测试代码如下

#include <stdio.h>
#include <pthread.h>
#include <assert.h>

void *thread1(void *pData)
{
	unsigned int i;
	printf("thread1 is running!\n");
	printf("info is %s\n", pData);
	
	for (i=0; i<30000; i++)
	{
		printf("%d\n", i);
	}
}

int main(int argc, char *argv[])
{
	pthread_t phifb0 = -1;	
	pthread_t phifb1 = -1;	
	
	char info[]="thead";

	pthread_create(&phifb0, 0, thread1, (void *)info);	
	

	if (-1 != phifb0)
	{
		pthread_join(phifb0, 0);
	}

	printf("main end\n");
}

编译时注意加上-lpthread库,即gcc main.c -o main -lpthread


上面代码如果将pthread_join注释掉,可以发现输出的i最后一个不是29999,说明线程thread1还未执行完成

以上代码还测试了线程传递参数的方法,和RTOS的是完全类似的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值