C++之多线程的使用(Windows)

来源:互联网 发布:lolita淘宝店 编辑:程序博客网 时间:2024/05/21 07:15

Windows下使用c++多线程头文件“pthread.h”,发现找不到头文件。
解决方法:
下载安装包:
pthreads-w32-2-8-0-release.exe点击下载

使用方法:
解压后,产生三个文件夹,需要使用文件夹Pre-built.2
include文件夹中的所有文件拷贝到C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\Include
lib文件夹中的所有的.lib文件拷贝到C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\lib
lib文件夹中的所有的.dll文件拷贝到C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin
最后使用时,在项目中添加属性-》连接器-》输入-》附加依赖项,
或者.cpp中添加代码#pragma comment(lib, “pthreadVC2.lib”)

总结:

//线程的开始与结束:pthread_t tid[5];//线程的声明int ret=pthread_create(thread, attr, start_routine, arg);//成功时,ret=0//无参数时,arg=NULL;有参数是,arg要转换为(void*)的引用pthread_exit(NULL)//连接与分离线程:pthread_join (threadid, status) pthread_detach (threadid) /*pthread_join() 子程序阻碍调用程序,直到指定的 threadid 线程终止为止。当创建一个线程时,它的某个属性会定义它是否是可连接的(joinable)或可分离的(detached)。只有创建时定义为可连接的线程才可以被连接。如果线程创建时被定义为可分离的,则它永远也不能被连接。*///锁的使用:pthread_mutex_t mutex;//声明pthread_mutex_lock(&mutex);//加锁pthread_mutex_unlock(&mutex);//释放锁pthread_mutex_destroy(&mutex);//注销锁//信号量的使用:pthread_cond_t tasks_cond; //声明pthread_cond_init(&tasks_cond, NULL); //初始化条件信号量pthread_cond_wait(&tasks_cond, &mutex); //等待pthread_cond_signal(&tasks_cond); //pthread_cond_destroy(&tasks_cond); //正常退出

下面附上两个Demo
Demo1:

#include <iostream>#include <pthread.h>using namespace std;#define NUM_THREADS 5int sum = 0; //定义全局变量,让所有线程同时写,这样就需要锁机制pthread_mutex_t sum_mutex; //互斥锁声明pthread_mutex_t mutex;void* say_hello(void* args){    pthread_mutex_lock(&sum_mutex); //先加锁,再修改sum的值,锁被占用就阻塞,直到拿到锁再修改sum;    cout << "This is thread:" << *((int *)args) << endl;    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);    //对应于pthread_create ,结束该线程    return NULL;}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        //pthread_create开始线程,如果不需要传递参数,第四个参数为NULL,如果传递参数,需要参数转换为(void*)的引用。        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 equal to " << sum << endl;    pthread_mutex_destroy(&sum_mutex); //注销锁    system("pause");}

运行结果为:

This is thread:0before sum is 0 in thread 0after sum is 0 in thread 0This is thread:3before sum is 3 in thread 3after sum is 3 in thread 3This is thread:4before sum is 4 in thread 4after sum is 4 in thread 4This is thread:2before sum is 2 in thread 2after sum is 2 in thread 2This is thread:1before sum is 1 in thread 1after sum is 1 in thread 1Finally sum is equal to 10

Demo2使用信号量:

#include <iostream>#include <pthread.h>#include <stdio.h>using namespace std;#define BOUNDARY 5int tasks = 10;pthread_mutex_t tasks_mutex; //互斥锁pthread_cond_t tasks_cond; //条件信号变量,处理两个线程间的条件关系,当task>5,hello2处理,反之hello1处理,直到task减为0void* say_hello2(void* args){    pthread_t pid = pthread_self(); //获取当前线程id    cout << "[" << pid.p << "] hello in thread " << *((int*)args) << endl;    bool is_signaled = false; //sign    while (1)    {        pthread_mutex_lock(&tasks_mutex); //加锁        if (tasks > BOUNDARY)        {            cout << "[" << pid.p << "] now task: " << tasks << " in thread " << *((int*)args) << endl;            --tasks; //modify        }        else if (!is_signaled)        {            cout << "[" << pid.p << "] 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;    }    cout << "线程2结束!!" << endl;    return NULL;}void* say_hello1(void* args){    pthread_t pid = pthread_self(); //获取当前线程id    cout << "[" << pid.p << "] hello in thread " << *((int*)args) << endl;    while (1)    {        pthread_mutex_lock(&tasks_mutex); //加锁        if (tasks > BOUNDARY)        {            cout << "[" << pid.p << "] pthread_cond_signal in thread " << *((int*)args) << endl;            pthread_cond_wait(&tasks_cond, &tasks_mutex); //wait:等待信号量生效,接收到信号,向hello2发出信号,跳出wait,执行后续         }        else        {            cout << "[" << pid.p << "] take task: " << tasks << " in thread " << *((int*)args) << endl;            --tasks;        }        pthread_mutex_unlock(&tasks_mutex); //解锁        if (tasks == 0)            break;    }    cout << "线程1结束!!" << endl;    return NULL;}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); //正常退出    system("pause");}

运行结果:

[00441B88] hello in thread 1[00441B88] pthread_cond_signal in thread 1[00441EB8] hello in thread 2[00441EB8] now task:10 in thread 2[00441EB8] now task:9 in thread 2[00441EB8] now task:8 in thread 2[00441EB8] now task:7 in thread 2[00441EB8] now task:6 in thread 2[00441EB8] pthread_cond_signal in thread 2[00441B88] now task:5 in thread 1[00441B88] now task:4 in thread 1[00441B88] now task:3 in thread 1[00441B88] now task:2 in thread 1[00441B88] now task:1 in thread 1线程1结束!!线程2结束!!
0 0