C++测试线程的使用

2016-04-29  本文已影响47人  zjunchao

测试线程使用

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

using namespace std;

#define NUM_THREADS     5


void *printHello(void *threadid){

    /*  如何将 void* 转化为int,
     *  1. 将 void* 转化为int*
     *  2. 直接从int *中,取出对应的值
     * */
    int tid;
    tid=*(int*)threadid;
    cout << "hello world! Thread ID,"<< tid << endl;
    pthread_exit(NULL);
}

int main() {

    pthread_t threads[NUM_THREADS];
    int rc;
    int i;
    for (i=0; i< NUM_THREADS; i++){
        cout<<"main() : creating thread,"<<endl;
        rc = pthread_create(&threads[i], NULL, printHello, (void *)&i);
        if(rc){
            cout << "Error: Unable to create therad,"<< rc << endl;
        }
    }
    pthread_exit(NULL);

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读