linux 的多线程编程,Linux 平台多线程编程实例

本文介绍了Linux下使用pthread库进行多线程编程的基本知识,包括线程创建、线程同步(互斥锁)以及参数传递。通过示例代码展示了如何创建和管理线程,以及如何通过互斥锁确保线程安全。此外,还探讨了如何将参数传递给线程函数,以适应不同场景的需求。最后,通过实际运行和测试,证明了多线程在提高程序效率方面的优势。
摘要由CSDN通过智能技术生成

最近在优化一个图像处理算法,算法中要对于不同的图片做相同的图像处理算法,不同图片之间的处理数据时独立的,因而很自然的想到利用多线程优化算法。

下面是一些学习代码

一 Linux下面的多线编程需要包含明白以下几点:

1 pthread_t

pthread_t在头文件/usr/include/bits/pthreadtypes.h中定义:

typedef unsigned long int pthread_t;

它是一个线程的标识符。

2 pthread_create

函数pthread_create用来创建一个线程,它的原型为:

extern int pthread_create __P ((pthread_t *__thread, __const pthread_attr_t *__attr,

void *(*__start_routine) (void *), void *__arg));

第一个参数为指向线程标识符的指针;

第二个参数用来设置线程属性;

第三个参数是线程运行函数的起始地址;

最后一个参数是运行函数的参数。

这里,我们的函数thread不需要参数,所以最后一个参数设为空指针。

第二个参数我们也设为空指针,这样将生成默认属性的线程。

对线程属性的设定和修改我们将在下一节 阐述。

当创建线程成功时,函数返回0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和EINVAL。

前者表示系统限制创建新的线程,例 如线程数目过多了;

后者表示第二个参数代表的线程属性值非法。

创建线程成功后,新创建的线程则运行参数三和参数四确定的函数,

原来的线程则继续运行下一行 代码。

3 pthread_join 和pthread_exit

函数pthread_join用来等待一个线程的结束。函数原型为:

extern int pthread_join __P ((pthread_t __th, void **__thread_return));

第一个参数为被等待的线程标识符;

第二个参数为一个用户定义的指针;

它可以用来存储被等待线程的返回值。这个函数是一个线程阻塞的函数,调用它的函数将 一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。一个线程的结束有两种途径,一种是像我们上面的例子一样,函数结束了,调用它的 线程也就结束了;

另一种方式是通过函数pthread_exit来实现。它的函数原型为:

extern void pthread_exit __P ((void *__retval)) __attribute__ ((__noreturn__));

唯一的参数是函数的返回代码,只要pthread_join中的第二个参数thread_return不是NULL,这个值将被传递给 thread_return。

最后要说明的是,一个线程不能被多个线程等待,否则第一个接收到信号的线程成功返回,其余调用pthread_join的线 程则返回错误代码ESRCH。

在这一节里,我们编写了一个最简单的线程,并掌握了最常用的三个函数pthread_create,pthread_join和pthread_exit。

4 互斥锁相关

互斥锁用来保证一段时间内只有一个线程在执行一段代码。

pthread_mutex_init函数用来生成一个互斥锁。NULL参数表明使用默认属性。如果需要声明特定属性的互斥锁,须调用函数 pthread_mutexattr_init。函数pthread_mutexattr_setpshared和函数 pthread_mutexattr_settype用来设置互斥锁属性。前一个函数设置属性pshared,它有两个取值, PTHREAD_PROCESS_PRIVATE;

PTHREAD_PROCESS_SHARED;

前者用来不同进程中的线程同步,后者用于同步本进程的 不同线程。

在上面的例子中,我们使用的是默认属性PTHREAD_PROCESS_ PRIVATE。后者用来设置互斥锁类型,可选的类型有

PTHREAD_MUTEX_NORMAL、

PTHREAD_MUTEX_ERRORCHECK、

PTHREAD_MUTEX_RECURSIVE和

PTHREAD _MUTEX_DEFAULT。

它们分别定义了不同的上所、解锁机制,一般情况下,选用最后一个默认属性。

pthread_mutex_lock和 pthread_mutex_unlock以及pthread_delay_np

pthread_mutex_lock声明开始用互斥锁上锁,此后的代码直至调用pthread_mutex_unlock为止,均被上锁,即同一时间只 能被一个线程调用执行。当一个线程执行到pthread_mutex_lock处时,如果该锁此时被另一个线程使用,那此线程被阻塞,即程序将等待到另一 个线程释放此互斥锁。

二 简单的代码实例

#include 

#include 

#include 

#include 

#include 

using namespace std;

pthread_t thread[2];

pthread_mutex_t mut;

double array[10][10];

double funtime(const string &str)

{

struct timeval tpstart,tpend;

double timeuse;

gettimeofday(&tpstart,NULL);

int loop = 1000000;

while(loop--)

{

for (int i = 0; i 

{

for(int j = 0; j 

{

array[i][j] = 0.63;

array[i][j] /= 0.96;

}

}

}

gettimeofday(&tpend,NULL);

timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;

timeuse/=1000;

cout <

return timeuse;

}

void *thread1(void *args)

{

cout<

funtime("thread1 fun");

cout<

pthread_exit(NULL);

}

void *thread2(void *args)

{

cout<

funtime("thread2 fun");

cout<

pthread_exit(NULL);

}

void thread_create(void)

{

int temp;

memset(&thread, 0, sizeof(thread));

if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0)

cout<

else

cout<

if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)

cout<

else

cout<

}

void thread_wait(void)

{

if(thread[0] !=0)

{

pthread_join(thread[0],NULL);

cout<

}

if(thread[1] !=0)

{

pthread_join(thread[1],NULL);

cout<

}

}

int main()

{

struct timeval tpstart,tpend;

double timeuse;

gettimeofday(&tpstart,NULL);

pthread_mutex_init(&mut,NULL);

cout<

thread_create();

cout<

thread_wait();

gettimeofday(&tpend,NULL);

timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;

timeuse/=1000;

cout <

cout <

funtime("main fun") + funtime("main fun") <

return 0;

}

测试运行:

linux 平台下面编译时需要加上 -lpthrad 如上面的代码test.cpp , 编译命令:

g++  -o test test.cpp -lpthread

可以看到两个线程都开始运行了,执行一次funtime函数需要花费1000ms左右的时间,单线程执行两次需要花费1953ms,而多线程利用两个线程并行执行花费的时间为1031ms,总的时间缩短了接近一倍。

81518540_2

为了验证多线程程序的执行结果是否正确,可以打印出矩阵观察。

修改代码:

#include 

#include 

#include 

#include 

#include 

using namespace std;

pthread_t thread[2];

pthread_mutex_t mut;

double array1[10][10];

double array2[10][10];

double array0[10][10];

double funtime(const string &str, const int index)

{

struct timeval tpstart,tpend;

double timeuse;

gettimeofday(&tpstart,NULL);

int loop = 1000000;

while(loop--)

{

for (int i = 0; i 

{

for(int j = 0; j 

{

if (index == 1)

{

array1[i][j] = 1;

array1[i][j] /= 2;

}else if(index == 2)

{

array2[i][j] = 2;

array2[i][j] /= 2;

}else

{

array0[i][j] = 3;

array0[i][j] /= 2;

}

}

}

}

gettimeofday(&tpend,NULL);

timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;

timeuse/=1000;

cout <

return timeuse;

}

void *thread1(void *args)

{

cout<

funtime("thread1 fun",1);

cout<

pthread_exit(NULL);

}

void *thread2(void *args)

{

cout<

funtime("thread2 fun",2);

cout<

pthread_exit(NULL);

}

void thread_create(void)

{

int temp;

memset(&thread, 0, sizeof(thread));

if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0)

cout<

else

cout<

if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)

cout<

else

cout<

}

void thread_wait(void)

{

if(thread[0] !=0)

{

pthread_join(thread[0],NULL);

cout<

}

if(thread[1] !=0)

{

pthread_join(thread[1],NULL);

cout<

}

}

void printresult()

{

cout <

for (int i = 0; i 

{

for (int j = 0; j 

{

cout <

}

cout <

}

cout <

for (int i = 0; i 

{

for (int j = 0; j 

{

cout <

}

cout <

}

cout <

for (int i = 0; i 

{

for (int j = 0; j 

{

cout <

}

cout <

}

}

int main()

{

struct timeval tpstart,tpend;

double timeuse;

gettimeofday(&tpstart,NULL);

pthread_mutex_init(&mut,NULL);

cout<

thread_create();

cout<

thread_wait();

gettimeofday(&tpend,NULL);

timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;

timeuse/=1000;

cout <

cout <

funtime("main fun",0) + funtime("main fun",0) <

printresult();

return 0;

}

81518540_3.png

81518540_4

81518540_5

从中可以看出线程执行结果是正确的

三 线程函数参数传递

funtime("thread1 fun",1);

funtime函数为线程调用中的主要执行函数,包含两个参数,都被写死了,实际中会有很多限制,因此需要考虑从线程的入口处传入参数。

前面的代码中,pthread_create(&thread[0], NULL, thread1, NULL)) != 0)中,第四个参数是线程执行函数需要传入的参数,在线程函数中void *thread1(void *args)中,只能允许传入一个参数,如果要传入多个参数,需要使用结构体,将多个参数组合为一个结构体一起传入。实例如下:

代码如下

#include 

#include 

#include 

#include 

#include 

using namespace std;

//thread function pamter

struct theradPamter{

int threadindex;

string str;

};

pthread_t thread[2];

pthread_mutex_t mut;

double array1[10][10];

double array2[10][10];

double array0[10][10];

double funtime(const string &str, const int index)

{

struct timeval tpstart,tpend;

double timeuse;

gettimeofday(&tpstart,NULL);

int loop = 1000000;

while(loop--)

{

for (int i = 0; i 

{

for(int j = 0; j 

{

if (index == 1)

{

array1[i][j] = 1;

array1[i][j] /= 2;

}else if(index == 2)

{

array2[i][j] = 2;

array2[i][j] /= 2;

}else

{

array0[i][j] = 3;

array0[i][j] /= 2;

}

}

}

}

gettimeofday(&tpend,NULL);

timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;

timeuse/=1000;

cout <

return timeuse;

}

void *thread1(void *args)

{

cout<

theradPamter *tp = (theradPamter *) args;

funtime(tp->str, tp->threadindex);

cout<

pthread_exit(NULL);

}

void *thread2(void *args)

{

cout<

theradPamter *tp = (theradPamter *) args;

funtime(tp->str, tp->threadindex);

cout<

pthread_exit(NULL);

}

void thread_create(theradPamter *tp1, theradPamter *tp2)

{

int temp;

memset(&thread, 0, sizeof(thread));

if((temp = pthread_create(&thread[0], NULL, thread1, (void *)tp1)) != 0)

cout<

else

cout<

if((temp = pthread_create(&thread[1], NULL, thread2, (void *)tp2)) != 0)

cout<

else

cout<

}

void thread_wait(void)

{

if(thread[0] !=0)

{

pthread_join(thread[0],NULL);

cout<

}

if(thread[1] !=0)

{

pthread_join(thread[1],NULL);

cout<

}

}

void printresult()

{

cout <

for (int i = 0; i 

{

for (int j = 0; j 

{

cout <

}

cout <

}

cout <

for (int i = 0; i 

{

for (int j = 0; j 

{

cout <

}

cout <

}

cout <

for (int i = 0; i 

{

for (int j = 0; j 

{

cout <

}

cout <

}

}

int main()

{

struct timeval tpstart,tpend;

double timeuse;

gettimeofday(&tpstart,NULL);

pthread_mutex_init(&mut,NULL);

cout<

theradPamter *tp1 = new theradPamter;

theradPamter *tp2 = new theradPamter;

tp1->threadindex = 1;

tp1->str = "thread1 fun";

tp2->threadindex = 2;

tp2->str = "thread2 fun";

thread_create(tp1, tp2);

cout<

thread_wait();

delete tp1;

tp1 = NULL;

delete tp2;

tp2 = NULL;

gettimeofday(&tpend,NULL);

timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;

timeuse/=1000;

cout <

cout <

funtime("main fun",0) + funtime("main fun",0) <

printresult();

return 0;

}

线程函数的参数需要传入一个void *类型的指针,因此需要在传递时,将tp指针强制转化为void*类型,传入 thread1(void *args) 中

在thread1(void *args)函数内,使用该指针时,在强制类型转换为threadPamter类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值