linux多线程——基础知识+实现

Posted 西邮菜

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux多线程——基础知识+实现相关的知识,希望对你有一定的参考价值。

在Linux中利用C语言实现多线程。利用函数pthread_create()、pthread_exit()、pthread_join()。

一、pthread_create()

#include <pthread.h>
int pthread_create(
                 pthread_t *restrict tidp,   //新创建的线程指向的内存单元。
                 const pthread_attr_t *restrict attr,  //线程属性,默认为NULL
                 void *(*start_rtn)(void *), //新创建的线程从start_rtn函数的地址开始运行
                 void *restrict arg //默认为NULL。若上述函数需要参数,将参数放入结构中并将地址作为arg传入。
                  );

二、pthread_exit()

void pthread_exit(void *retval);线程退出,并可以设置返回的状态码。

return、exit、pthread_exit的功能不一样:

1.pthread_exit()用于线程退出,可以指定返回值,以便其他线程通过pthread_join()函数获取该线程的返回值
2.return,是函数返回,不一定是线程函数哦! 只有线程函数return,线程才会退出
3.exit()是进程退出,如果在线程函数中调用exit,那改线程的进程也就挂了,会导致该线程所在进程的其他线程也挂掉。
 

三、pthread_join()

pthread_join()方法后面的代码,只有等到子线程结束了才能执行。

int pthread_join(
               pthread_t tid, //需要等待的线程,指定的线程必须位于当前的进程中,而且不得是分离线程
               void **status  //线程tid所执行的函数返回值(返回值地址需要保证有效),其中status可以为NULL
                 );

四、多线程例子

4.1 第一个例子

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

void *func0()

	printf("this is thread0\\n");
	pthread_exit((void *)0);  //退出线程并返回状态码


void *func1()

	printf("this is thread1\\n");
	pthread_exit((void *)1);


int main()

	int err;
	pthread_t tid0,tid1;
	void *ret;
	err=pthread_create(&tid0,NULL,func0,NULL); //创建一个线程叫线程号为tid0
	if(err)
	
		printf("error");
		exit(1);
	
	err=pthread_create(&tid1,NULL,func1,NULL);//创建一个线程叫线程号为tid1
	if(err)
	
		printf("error");
		exit(2);
	
	err=pthread_join(tid0,&ret);//阻塞进程,等待func1执行完
	if(err)
	
		printf("eror");
		exit(1);
	
	printf("tid0 code:%ld\\n",(long)ret);
	err=pthread_join(tid1,&ret);    //阻塞进程,等待func1执行完
	if(err)
	
		printf("dw");
		exit(1);
	
	printf("tid1 code :%ld\\n",(long)ret);
	exit(0);

利用命令gcc thread_join.c -o main -lpthread(这个必须加)。

./main执行结果如下。

 可以看到,线程都正常运行结束,并且返回的状态码进程也捕获到了。

4.2 第二个例子

证明线程是运行在同一个父进程下的。

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *func();
void printtid(char *s);
void printtid(char *s)

	pthread_t tid;
	pid_t pid;
	pid=getpid();
	tid=pthread_self();
	printf("%s:pid=%10d  tid=%ld\\n",s,pid,tid);


void *func()

	printtid("child0");
	pthread_exit(NULL);

void *func1()

	printtid("child1");
	pthread_exit(NULL);

int main()

	int err;
	pthread_t tid0,tid1;
	err=pthread_create(&tid0,NULL,func,NULL);
	if(err)
	
		printf("eror");
		exit(1);
	
	err=pthread_create(&tid1,NULL,func1,NULL);
	if(err)
	
		printf("eror");
		exit(1);
	
	printtid("main");
    sleep(1);  //等一秒,这里没使用pthread_join,防止没执行线程直接退出。
	exit(0);

执行效果如下:可以看到所有线程的进程号都是相同的,所以说明他们是同一个进程下的不同线程。

 

以上是关于linux多线程——基础知识+实现的主要内容,如果未能解决你的问题,请参考以下文章

多线程基本知识

多线程的知识

Linux 多线程编程

Linux C 程序设计多线程基础篇

java多线程实例---很有用 详细介绍

java多线程实例---很有用 详细介绍