您的位置:首页 > 运维架构 > Linux

linux创建线程

2015-09-19 23:27 405 查看
线程:

进程:资源分配的基本单位

线程:系统调度的基本单位

线程创建: pthread_create (&tid 返回子线程ID, 属性,子线程函数入口(函数指针),函数传入参数)

sqrt :-lm --> - link libm.a

pthread:-lpthread -> -link libpthread.a

线程创建时候要注意属性:

优先级 、调度、分离状态(detach? joined?)、栈大小及起始地址,没有特殊要求就设成NULL

系统默认是个join线程,非分离

子线程函数入口 是有返回值void *的, 也可以传入参数,具体的参数类型是第四个参数传入

线程的回收: 只针对的是非分离线程 pthread_join

注意: 1:主线程会先继续执行;

如果主线程没有等待回收或者其它阻塞,主线程结束的时候,整个进程也就结束了

2:如果线程中调用了exit类的函数,会直接退出整个进程;

return (void *)0 ; 则返回到调用的线程中。

实例:

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

int a=0;

void *myThread1(void)
{
int i;
for(i=0; i<3; i++)
{
a++;
printf("pthread1: a=%d   ",a);
printf("This is the 1st pthread,pid is %d;tid1=%lu\n",getpid(),pthread_self());
sleep(1);//Let this thread to sleep 1 second,and then continue to run
return (void *)0;// exit (0);
}
}

void *myThread2(void)
{
int i;
for (i=0; i<3; i++)
{
a++;
printf("pthread2: a=%d   ",a);
printf("This is the 2st pthread,pid is %d;tid2=%lu\n",getpid(),pthread_self());
sleep(1);
}
}

int main()
{
int i=0, ret=0;
pthread_t tid1,tid2;

printf("main creat thread1\n");
ret = pthread_create(&tid1, NULL, (void*)myThread1, NULL);
if (ret)
{
perror("Create pthread1 error:\n");
return 1;
}
printf("main creat thread2\n");
ret = pthread_create(&tid2, NULL,(void*) myThread2, NULL);
if (ret)
{
perror("Create pthread2 error:");
return 1;
}
a++;
printf("pthread main : a=%d  ",a);
printf("This is main pthread,process id is %d;tid=%lu\n",getpid(),pthread_self());
pthread_join(tid1, NULL);
printf("tid1 end \n");
pthread_join(tid2, NULL);
printf("thread1&thread2 end, a=%d\n",a);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: