C++:多线程操作

多线程是多任务处理的一种特殊形式,多任务处理允许让目标设备同时运行两个或两个以上的程序。一般情况下,两种类型的多任务处理:基于进程和基于线程。

基于进程的多任务处理是程序的并发执行。
基于线程的多任务处理是同一程序的片段的并发执行。

多线程程序包含可以同时运行的两个或多个部分。这样的程序中的每个部分称为一个线程,每个线程定义了一个单独的执行路径。

线程创建

#include <pthread.h>

pthread_create (pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg) 

参数解析:

pthread_t *thread                 要创建的线程的线程id指针
const pthread_attr_t *attr        创建线程时的线程属性
void *(*start_routine) (void *)   返回值是void类型的指针函数
void *arg                         指针函数的行参

线程终止

void pthread_exit(void *rval_ptr);                   /*rval_ptr 线程退出返回的指针*/  

线程等待

int pthread_join(pthread_t thread,void **rval_ptr);  /*成功结束进程返回0,否则返回错误编码*/  

示例代码:

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

using namespace std;

#define NUM 3

struct thread_message
{
    int id;
    char* message;
};

void* fun(void* arg)
{
    struct thread_message* data;
    data = (struct thread_message*)arg;            // 线程参数传递

    cout << "Message information: " << data->message << "[" << data->id << "]" << endl;

    pthread_exit(NULL);
}

int main(void)
{
    pthread_t pid[NUM];
    void* status;

    struct thread_message td[NUM];

    for(int i=0; i<NUM; i++)
    {
        td[i].id = i;
        td[i].message = (char*)"This is message";

        if(pthread_create(&pid[i], NULL, fun, (void*)&td[i]))    // 线程创建、传参与判断
        {
            cout << "Thread[" << i << "] creat fail" << endl;
        }
        else
        {
            cout << "Thread[" << i << "] creat success" << endl;
        }

        if(pthread_join(pid[i], &status) == 0)                  // 线程退出等待判断
            cout << "Thread[" << i << "] exit success" << endl;
        else
            cout << "Thread[" << i << "] exit fail" << endl;

        cout << endl;

        usleep(20);
    }

    return 0;
}
[john@bogon C++]$ g++ thread.cc -lpthread
[john@bogon C++]$ ./a.out 
Thread[0] creat success
Message information: This is message[0]
Thread[0] exit success

Thread[1] creat success
Message information: This is message[1]
Thread[1] exit success

Thread[2] creat success
Message information: This is message[2]
Thread[2] exit success

猜你喜欢

转载自blog.csdn.net/keyue123/article/details/79172084