线程的基本概念和相关函数

线程的基本概念和相关函数

pthread_self函数

头文件:
#include <pthread.h>
函数原型:
pthread_t pthread_self(void);
功能:
获得线程自身的ID。
返回值:
pthread_t的类型为unsigned long int,所以在打印的时候要使用%lu方式

pthread_create函数

头文件:
#include<pthread.h>
函数原型:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
 void *(*start_routine) (void *), void *arg);
功能:
创建线程
参数:
thread 指向线程标识符(ID)的指针。
attr       用来设置线程属性,一般为NULL
start_routine 线程运行函数的起始地址。
arg         运行函数的参数。
返回值:
线程创建成功,则返回0。若线程创建失败,则返回出错编号,并且*thread中的内容是未定义的。

举例:循环创建多个线程

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

void *tfn(void *arg)
{
	int i;

	i = (int)arg;
	sleep(i);	 //通过i来区别每个线程
	printf("I'm %dth thread, Thread_ID = %lu\n", i+1, pthread_self());

	return NULL;
}

int main(int argc, char *argv[])
{
	int n = 5, i;
	pthread_t tid;

	if (argc == 2)
		n = atoi(argv[1]);

	for (i = 0; i < n; i++) {
		pthread_create(&tid, NULL, tfn, (void *)i);//注意此处必须是值传递
		//将i转换为指针,在tfn中再强转回整形。
	}
	sleep(n);
	printf("I am main, and I am not a process, I'm a thread!\n" 
			"main_thread_ID = %lu\n", pthread_self());

	return 0;
}

pthread_exit函数

头文件: 
#include <pthread.h>
函数原型:
void pthread_exit(void *retval);
功能:
线程通过调用pthread_exit函数终止执行,就如同进程在结束时调用exit函数一样。

注意:在main线程中调用pthread_exit会起到只让main线程退出,但是保留进程资源,供其他由main创建的线程使用,直至所有线程都结束,但在其他线程中不会有这种效果

主线程、子线程调用exit, pthread_exit,互相产生的影响。

1、在主线程中,在main函数中return了或是调用了exit函数,则主进程退出,且整个进程也会终止,此时进程中的所有线程也将终止。因此要避免main函数过早结束。

2、在主线程中调用pthread_exit, 则仅仅是主线程结束,进程不会结束,进程内的其他线程也不会结束,直到所有线程结束,进程才会终止。

3、在任何一个线程中调用exit函数都会导致进程结束。进程一旦结束,那么进程中的所有线程都将结束。

pthread_join函数

头文件:
 #include <pthread.h>
函数原型:
int pthread_join(pthread_t thread, void **retval);
功能:
pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数
返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数:
thread: 线程标识符,即线程ID,标识唯一线程。
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 
0代表成功。 失败,返回的则是错误号。

pthread_join函数与pthread_exit函数区别

pthread_join一般是主线程来调用,用来等待子线程退出,因为是等待,所以是阻塞的,一般主线程会依次join所有它创建的子线程。
pthread_exit一般是子线程调用,用来结束当前线程。
子线程可以通过pthread_exit传递一个返回值,而主线程通过pthread_join获得该返回值,从而判断该子线程的退出是正常还是异常。

发布了46 篇原创文章 · 获赞 64 · 访问量 8777

猜你喜欢

转载自blog.csdn.net/qq_43799957/article/details/105401387