Linux 平台多线程编程实例

时间:2021-04-09 18:31:38

转载请注明出去 http://blog.csdn.net/adong76/article/details/39828585

参考博客:

http://www.cnblogs.com/armlinux/archive/2010/05/28/2396997.html

http://blog.csdn.net/hitwengqi/article/details/8015646

http://www.vimer.cn/2009/11/linux%E4%B8%8B%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E7%AD%89%E5%BE%85%E8%AF%A6%E8%A7%A3.html

http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html

http://www.cnblogs.com/vamei/archive/2012/10/09/2715393.html

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

下面是一些学习代码

一 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 <pthread.h>
#include <iostream>
#include <unistd.h>
#include <sys/time.h>
#include <string>
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 < 10; ++i)
        {
            for(int j = 0; j < 10;++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 << str << " timeuse: " << timeuse << " ms" << endl;
    return timeuse;
}


void *thread1(void *args)
{
    cout<< "thread1 : I'm thread 1" << endl;
    funtime("thread1 fun");
    cout<< "thread1 :main function is waiting me" << endl;
    pthread_exit(NULL);
}

void *thread2(void *args)
{
    cout<< "thread2 : I'm thread 2" << endl;
    funtime("thread2 fun");
    cout<< "thread2 :main function is waiting me" << endl;
    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<<"thread1 is created failed" << endl;
    else
        cout<<"thread1 is created " << endl;
    if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)  
        cout<<"thread2 created failed" << endl;
    else
        cout<<"thread2 is created" << endl;
}

void thread_wait(void)
{
    if(thread[0] !=0)
    {     
        pthread_join(thread[0],NULL);
        cout<<("thread1 is end \n");
    }
    if(thread[1] !=0) 
    {  
        pthread_join(thread[1],NULL);
        cout<<("thread2 is end \n");
    }
}


int main()
{
    struct timeval tpstart,tpend;
    double timeuse;
    gettimeofday(&tpstart,NULL);

    pthread_mutex_init(&mut,NULL);
    cout<<"main function is created thread" << endl;
    thread_create();
    cout<<"main function is waiting thread" << endl;
    thread_wait();

    gettimeofday(&tpend,NULL);
    timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
    timeuse/=1000;
    cout << "MulThread " << " timeuse: " << timeuse << " ms" << endl;

    cout << "signle thread time using: " << 
    funtime("main fun") + funtime("main fun") << " ms" << endl;

    return 0;
}




测试运行:

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

  g++  -o test test.cpp -lpthread

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

Linux 平台多线程编程实例

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

修改代码:

#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <sys/time.h>
#include <string>
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 < 10; ++i)
        {
            for(int j = 0; j < 10;++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 << str << " timeuse: " << timeuse << " ms" << endl;
    return timeuse;
}


void *thread1(void *args)
{
    cout<< "thread1 : I'm thread 1" << endl;
    funtime("thread1 fun",1);
    cout<< "thread1 :main function is waiting me" << endl;
    pthread_exit(NULL);
}

void *thread2(void *args)
{
    cout<< "thread2 : I'm thread 2" << endl;
    funtime("thread2 fun",2);
    cout<< "thread2 :main function is waiting me" << endl;
    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<<"thread1 is created failed" << endl;
    else
        cout<<"thread1 is created " << endl;
    if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)  
        cout<<"thread2 created failed" << endl;
    else
        cout<<"thread2 is created" << endl;;
}

void thread_wait(void)
{
    if(thread[0] !=0)
    {     
        pthread_join(thread[0],NULL);
        cout<<("thread1 is end \n");
    }
    if(thread[1] !=0) 
    {  
        pthread_join(thread[1],NULL);
        cout<<("thread2 is end \n");
    }
}


void printresult()
{
    cout << "array1" << endl;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            cout << " " << array1[i][j];
        }
        cout << endl;
    }

    cout <<"array2" <<endl;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            cout << " " << array2[i][j];
        }
        cout << endl;
    }

    cout <<"array0" <<endl;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            cout << " " << array0[i][j];
        }
        cout << endl;
    }

}


int main()
{
    struct timeval tpstart,tpend;
    double timeuse;
    gettimeofday(&tpstart,NULL);

    pthread_mutex_init(&mut,NULL);
    cout<<"main function is created thread" << endl;
    thread_create();
    cout<<"main function is waiting thread" << endl;
    thread_wait();

    gettimeofday(&tpend,NULL);
    timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
    timeuse/=1000;
    cout << "MulThread " << " timeuse: " << timeuse << " ms" << endl;

    cout << "signle thread time using: " << 
    funtime("main fun",0) + funtime("main fun",0) << " ms" << endl;

    printresult();

    return 0;
}


Linux 平台多线程编程实例

Linux 平台多线程编程实例

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

三 线程函数参数传递

funtime("thread1 fun",1);

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

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

代码如下

#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <sys/time.h>
#include <string>
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 < 10; ++i)
        {
            for(int j = 0; j < 10;++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 << str << " timeuse: " << timeuse << " ms" << endl;
    return timeuse;
}


void *thread1(void *args)
{
    cout<< "thread1 : I'm thread 1" << endl;
    theradPamter *tp = (theradPamter *) args;
    funtime(tp->str, tp->threadindex);
    cout<< "thread1 :main function is waiting me" << endl;
    pthread_exit(NULL);
}

void *thread2(void *args)
{
    cout<< "thread2 : I'm thread 2" << endl;
    theradPamter *tp = (theradPamter *) args;
    funtime(tp->str, tp->threadindex);
    cout<< "thread2 :main function is waiting me" << endl;
    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<<"thread1 is created failed" << endl;
    else
        cout<<"thread1 is created " << endl;
    if((temp = pthread_create(&thread[1], NULL, thread2, (void *)tp2)) != 0)  
        cout<<"thread2 created failed" << endl;
    else
        cout<<"thread2 is created" << endl;

}

void thread_wait(void)
{
    if(thread[0] !=0)
    {     
        pthread_join(thread[0],NULL);
        cout<<("thread1 is end \n");
    }
    if(thread[1] !=0) 
    {  
        pthread_join(thread[1],NULL);
        cout<<("thread2 is end \n");
    }
}


void printresult()
{
    cout << "array1" << endl;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            cout << " " << array1[i][j];
        }
        cout << endl;
    }

    cout <<"array2" <<endl;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            cout << " " << array2[i][j];
        }
        cout << endl;
    }

    cout <<"array0" <<endl;
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            cout << " " << array0[i][j];
        }
        cout << endl;
    }

}


int main()
{
    struct timeval tpstart,tpend;
    double timeuse;
    gettimeofday(&tpstart,NULL);

    pthread_mutex_init(&mut,NULL);
    cout<<"main function is created thread" << endl;

    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<<"main function is waiting thread" << endl;
    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 << "MulThread " << " timeuse: " << timeuse << " ms" << endl;

    cout << "signle thread time using: " << 
    funtime("main fun",0) + funtime("main fun",0) << " ms" << endl;

    printresult();

    return 0;
}


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

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