C/C++ 多线程编程方法

我们在使用C/C++进行多线程编程时,可以使用不同的函数库,比如Windows API 的 CreateThread在对windows窗体进行多线程编程时可以非常方便的使用,还有C++ 11标准的std::thread(function)更能方便的使用,直接支持函数的绑定。但是因为是C++ 11标准,需要使用 VS2012版本以上的编译器才支持。

我们主要讲解 pthread这个库方法,这个是Linux标准的多线程方法,windows也进行了移植。我们一步步深入讲解。
  • 1 配置pthread
    和常见的配置方式一样,首先配置 include目录(包含目录),library目录(库目录),链接器的输入中的“附加依赖项”输入所有的lib文件名称。然后把dll文件拷贝到程序的运行目录下。
  • 2测试配置是否成功
 #include "stdafx.h"
 //#include <thread> C++ 11 标准
 #include <pthread.h>
 #include <iostream>
 using namespace std;

 class Test
{
public:
    static void* MyMethod(void*)
    {
        cout<<"类成员函数"<<endl;
        return NULL;
    }
};
void* test(void* args)
{
return NULL;
}


int _tmain(int argc, _TCHAR* argv[])
{

for (int i=0;i<NUM_THREADS;i++)
{
    pthread_t pid;
    pthread_create(&pid, &attr, test, NULL); //调用普通函数
    pthread_create(&pid,&attr,Test::MyMethod,NULL);//调用类的静态成员函数
}
getchar();
return 0;
}

需要注意的是多线程如果需要传递参数,方法是 将需要的参数封装成一个 struct 结构体 data,然后 在调用pthread_create方法时,最后一个参数,使用转换方法(void*)data; 在调用方法中,将void*数据转化为结构体。

  • 3 线程创建时属性参数的设置pthread_attr_t及join功能的使用
    线程的属性由结构体pthread_attr_t进行管理。
typedef struct
{
    int detachstate;     线程的分离状态
    int  schedpolicy;   线程调度策略
    struct sched_param  schedparam;   线程的调度参数
    int inheritsched; 线程的继承性 
    int scope; 线程的作用域 
    size_t guardsize; 线程栈末尾的警戒缓冲区大小 
    int stackaddr_set; void * stackaddr; 线程栈的位置 
    size_t stacksize; 线程栈的大小
}pthread_attr_t;

测试代码如下:

#include <iostream>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

void* say_hello( void* args )
{
    cout << "hello in thread " << *(( int * )args) << endl;
    int status = 10 + *(( int * )args); //线程退出时添加退出的信息,status供主程序提取该线程的结束信息
    pthread_exit( ( void* )status ); 
}

int main()
{
    pthread_t tids[NUM_THREADS];
    int indexes[NUM_THREADS];

    pthread_attr_t attr; //线程属性结构体,创建线程时加入的参数
    pthread_attr_init( &attr ); //初始化
    pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能,joinable是默认的属性值
    for( int i = 0; i < NUM_THREADS; ++i )
    {
        indexes[i] = i;
        int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) );
        if( ret != 0 )
        {
        cout << "pthread_create error:error_code=" << ret << endl;
    }
    } 
    pthread_attr_destroy( &attr ); //释放内存 
    void *status;
    for( int i = 0; i < NUM_THREADS; ++i )
    {
    int ret = pthread_join( tids[i], &status ); //主程序join每个线程后取得每个线程的退出信息status
    if( ret != 0 )
    {
        cout << "pthread_join error:error_code=" << ret << endl;
    }
    else
    {
        cout << "pthread_join get status:" << (long)status << endl;
    }
    }
}
  • 4.线程同步-mutex 互斥量
    mutex互斥量用于多个线程在使用资源的时候,使用互斥锁,保证某一个线程执行结束后才能让其他线程使用这个资源(变量)。比如常用的场景是 防止读脏数据。
#include <iostream>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

int sum = 0; //定义全局变量,让所有线程同时写,这样就需要锁机制
pthread_mutex_t sum_mutex; //互斥锁

void* say_hello( void* args )
{
    cout << "hello in thread " << *(( int * )args) << endl;
    pthread_mutex_lock( &sum_mutex ); //先加锁,再修改sum的值,锁被占用就阻塞,直到拿到锁再修改sum;
    cout << "before sum is " << sum << " in thread " << *( ( int* )args ) << endl;
    sum += *( ( int* )args );
    cout << "after sum is " << sum << " in thread " << *( ( int* )args ) << endl;
    pthread_mutex_unlock( &sum_mutex ); //释放锁,供其他线程使用
    pthread_exit( 0 ); 
}

int main()
{
    pthread_t tids[NUM_THREADS];
    int indexes[NUM_THREADS];

    pthread_attr_t attr; //线程属性结构体,创建线程时加入的参数
    pthread_attr_init( &attr ); //初始化
    pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能
    pthread_mutex_init( &sum_mutex, NULL ); //对锁进行初始化    

    for( int i = 0; i < NUM_THREADS; ++i )
    {
        indexes[i] = i;
        int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) ); //5个进程同时去修改sum
        if( ret != 0 )
        {
        cout << "pthread_create error:error_code=" << ret << endl;
    }
    } 
    pthread_attr_destroy( &attr ); //释放内存 
    void *status;
    for( int i = 0; i < NUM_THREADS; ++i )
    {
    int ret = pthread_join( tids[i], &status ); //主程序join每个线程后取得每个线程的退出信息status
    if( ret != 0 )
    {
        cout << "pthread_join error:error_code=" << ret << endl;
    }
    }
    cout << "finally sum is " << sum << endl;
    pthread_mutex_destroy( &sum_mutex ); //注销锁
}
  • 5.线程同步-signal 信号量

信号量的作用是多个线程在执行的时候,某些线程必须等到其他线程先做完才能执行,有一定的执行顺序,否则会出现错误。使用的是信号量的P V操作。
信号量的操作有signal和wait,本例子采用条件信号变量pthread_cond_t tasks_cond;
信号量的实现也要给予锁机制。

#include <iostream>
#include <pthread.h>
#include <stdio.h>

using namespace std;

#define BOUNDARY 5

int tasks = 10;
pthread_mutex_t tasks_mutex; //互斥锁
pthread_cond_t tasks_cond; //条件信号变量,处理两个线程间的条件关系,当task>5,hello2处理,反之hello1处理,直到task减为0

void* say_hello2( void* args )
{
    pthread_t pid = pthread_self(); //获取当前线程id
    cout << "[" << pid << "] hello in thread " <<  *( ( int* )args ) << endl;

    bool is_signaled = false; //sign
    while(1)
    {
    pthread_mutex_lock( &tasks_mutex ); //加锁
    if( tasks > BOUNDARY )
    {
        cout << "[" << pid << "] take task: " << tasks << " in thread " << *( (int*)args ) << endl;
        --tasks; //modify
    }
    else if( !is_signaled )
    {
        cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl;
        pthread_cond_signal( &tasks_cond ); //signal:向hello1发送信号,表明已经>5
        is_signaled = true; //表明信号已发送,退出此线程
    }
    pthread_mutex_unlock( &tasks_mutex ); //解锁
    if( tasks == 0 )
        break;
    }    
}

void* say_hello1( void* args )
{
    pthread_t pid = pthread_self(); //获取当前线程id
    cout << "[" << pid << "] hello in thread " <<  *( ( int* )args ) << endl;

    while(1)
    {
        pthread_mutex_lock( &tasks_mutex ); //加锁
        if( tasks > BOUNDARY )
        {
        cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl;
        pthread_cond_wait( &tasks_cond, &tasks_mutex ); //wait:等待信号量生效,接收到信号,向hello2发出信号,跳出wait,执行后续 
        }
        else
        {
        cout << "[" << pid << "] take task: " << tasks << " in thread " << *( (int*)args ) << endl;
            --tasks;
    }
        pthread_mutex_unlock( &tasks_mutex ); //解锁
        if( tasks == 0 )
            break;
    } 
}


int main()
{
    pthread_attr_t attr; //线程属性结构体,创建线程时加入的参数
    pthread_attr_init( &attr ); //初始化
    pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能
    pthread_cond_init( &tasks_cond, NULL ); //初始化条件信号量
    pthread_mutex_init( &tasks_mutex, NULL ); //初始化互斥量
    pthread_t tid1, tid2; //保存两个线程id
    int index1 = 1;
    int ret = pthread_create( &tid1, &attr, say_hello1, ( void* )&index1 );
    if( ret != 0 )
    {
        cout << "pthread_create error:error_code=" << ret << endl;
    }
    int index2 = 2;
    ret = pthread_create( &tid2, &attr, say_hello2, ( void* )&index2 );
    if( ret != 0 )
    {
        cout << "pthread_create error:error_code=" << ret << endl;
    }
    pthread_join( tid1, NULL ); //连接两个线程
    pthread_join( tid2, NULL ); 

    pthread_attr_destroy( &attr ); //释放内存 
    pthread_mutex_destroy( &tasks_mutex ); //注销锁
    pthread_cond_destroy( &tasks_cond ); //正常退出
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值