C++测试线程的使用

测试线程使用

#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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容