C++:类中创建线程


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;

class Test
{
public:

    Test():sum(0){}

    // static  void * insert_pth(void*);
    friend  void * insert_pth(void*);
    void lanch1();

private:
    int sum;
};

// void * Test::insert_pth(void* __this)
void* insert_pth(void* __this)
{
    Test * _this =(Test *)__this;
    sleep(2);
    _this->sum+=1;
    printf("%d insert.....\n",_this->sum);
}

void Test::lanch1()
{
    pthread_t pth;
    pthread_create(&pth,NULL,insert_pth,(void*)this);
}

int main()
{
    Test t;
    t.lanch1();

    pthread_t pid;
    pthread_create(&pid, NULL, insert_pth, (void*)&t);
    // pthread_create(&pid, NULL, Test::insert_pth, (void*)&t);

    pthread_join(pid, NULL);

    sleep(5);
    return 0;
}
posted @ 2019-09-23 16:20  sfdevs  阅读(683)  评论(0编辑  收藏  举报