【发布时间】:2016-10-31 14:38:33
【问题描述】:
我正在学习pthread,我有几个问题。
这是我的代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define NUM_THREADS 10
using namespace std;
void *PrintHello(void *threadid)
{
int* tid;
tid = (int*)threadid;
for(int i = 0; i < 5; i++){
printf("Hello, World (thread %d)\n", *tid);
}
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
int t;
int* valPt[NUM_THREADS];
for(t=0; t < NUM_THREADS; t++){
printf("In main: creating thread %d\n", t);
valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
代码运行良好,我不调用pthread_join。所以我想知道,pthread_join 是必须的吗?
另一个问题是:
valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
等于:
rc = pthread_create(&threads[t], NULL, PrintHello, &i);
【问题讨论】:
-
第二个问题的答案:呃,这两个在我看来完全不同。我的建议是使用
reinterpret_cast<void *>(i),因为这是 C++ 而不是 C,因为问题已被标记。 -
这里讨论了将值传递给
pthread_create:stackoverflow.com/questions/8487380/… -
一个线程在你加入它时被“释放”,或者当它完成时它被分离。如果它没有分离并且你不加入它,你就是在泄漏它。
-
1.
pthread_join是必须的,因为主线程(创建其他线程的线程)可能会在创建的线程完成之前完成执行,并且您通常会为冗长的任务创建线程。这也是一种同步线程的方法。 2. 你真的不需要 valPt(而且你现在也在泄漏 valPt[t])。