本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路。
十三、Linux多线程
在同一个进程中,可以运行多个线程,运行于同一个进程中的多个线程,它们彼此之间使用相同的地址空间,共享全局变量和对象,启动一个线程所消耗的资源比启动一个进程所消耗的资源要少。
在Linux下,采用pthread_create函数来创建一个新的线程,函数声明:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);thread为为指向线程的地址。attr用于设置线程属性,一般为空,表示使用默认属性。start_routine是线程运行函数的地址,填函数名就可以了。arg是线程运行函数的参数。新创建的线程从start_routine函数的地址开始运行,该函数只有一个无类型指针参数arg。若要想向start_routine传递多个参数,可以将多个参数放在一个结构体中,然后把结构体的地址作为arg参数传入,但是要非常慎重,程序员一般不会这么做。
在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库。
线程的终止:
如果进程中的任一线程调用了exit,则整个进程会终止,所以,在线程的start_routine函数中,不能采用exit。
线程的终止有三种方式:
1)线程的start_routine函数代码结束,自然消亡。
2)线程的start_routine函数调用pthread_exit结束。
3)被主进程或其它线程中止。
void pthread_exit(void *retval);
参数retval填空,即0。
创建线程:
#include <pthread.h>
pthread_create (thread,attr,start_routine,arg)
thread:指向线程标识符指针;attr:一个不透明的属性对象,默认NULL; start_routine:线程运行函数起始地址;arg:运行函数的参数,若无传递参数,则NULL
终止线程:
#include <pthread.h>
pthread_exit (status)
线程示例:
#include <iostream> // 必须的头文件
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5 // 线程的运行函数
void* say_hello(void* args)
{ cout << "Hello Runoob!" << endl; return 0; }
int main()
{ // 定义线程的 id 变量,多个变量使用数组
pthread_t tids[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; ++i)
{ //参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
if (ret != 0)
{ cout << "pthread_create error: error_code=" << ret << endl; } } //等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
pthread_exit(NULL); }
本文转载于: 版权所有 (c) 2008-2020,码农有道,C语言技术网(www.freecplus.net)