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的是完全类似的