linux学习笔记8 线程

1.创建线程

函数原型:int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

参数描述:thread是线程id,是传出参数,只需要提供一个地址即可

attr是线程属性,一般为NULL

start_routine是线程执行的函数,函数定义为void *func (void *)。

arg是线程执行函数的参数

程序举例:创建一个进程

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>


using namespace std;
void *thr(void * agr)//void *定义的是无类型指针,可以将任意一种类型的指针赋给无类型指针
{
	sleep(1);
	cout<<"i am a thread, pid = "<<getpid()<<" thread = "<<pthread_self()<<endl;
        return NULL;//线程中可以使用return,但是主控线程不能使用return,这样就会把进程给结束了
}

int main()
{
	pthread_t tid;
	pthread_create(&tid, NULL, thr, NULL);
	cout<<"i am a main thread, pid ="<<getpid()<<" thread = "<<pthread_self()<<endl;
	sleep(2);//如果这句程序没有,整个进程就会结束了,那么建立的线程根本没有机会执行。
//这里可以把sleep函数换成pthread_create(NULL),效果一样。
}

2.回收线程

函数原型:int pthread_join(pthread_t thread, void **retval);

函数描述:thread是要回收的线程号, retval是线程执行函数的返回值。

程序举例:

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>


using namespace std;
void *thr(void * agr)
{
	sleep(1);
	cout<<"i am a thread, pid = "<<getpid()<<"thread = "<<pthread_self()<<endl;
	return (void*)100;
}

int main()
{
	pthread_t tid;
	pthread_create(&tid, NULL, thr, NULL);
	cout<<"i am a main thread, pid ="<<getpid()<<"thread = "<<pthread_self()<<endl;
	void *ret;
	pthread_join(tid, &ret);//这里的ret就是100。
	sleep(2);
}

猜你喜欢

转载自blog.csdn.net/qq_34489443/article/details/87989982