我正在研究 llnl.computing.gov pthreads 教程中的一些简单 pthread 示例。网站上的程序打印出threadid的地址,但是我想把id的地址传给PrintHello,然后使用dereference这个地址来获取id。我认为每个线程都应该打印 8(线程数)。代码是
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 8
void *PrintHello(void *threadid)
{
long *taskid = (long *)threadid;
sleep(1);
printf("Hello from thread %ld\n", *taskid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0;t<NUM_THREADS;t++) {
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &t);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
当我在 Cygwin 中编译和运行它时,它会出现堆栈损坏错误。如果我将 PrintHello 重写为:
void *PrintHello(void *threadid)
{
long taskid = (long) threadid;
sleep(1);
printf("Hello from thread %ld\n", taskid);
pthread_exit(NULL);
}
它不会出现段错误,它只会打印地址,我想取消引用该地址并从 main 中获取 t 的值。
有没有人对如何实现该目标有一些指示?我知道我可以将 t
传递给 pthread_create
而不是 &t
但我想以这种方式进行学习。
最佳答案
当您从主线程调用 pthread_exit(NULL)
时,它会终止该线程。此时,main
函数中的任何局部变量(包括 t
)都将被销毁,无法再使用。
如果主线程在所有工作线程使用 t
完成之前退出(通过您通过 pthread_create
传递给它们的指针),您的程序会表现出未定义的行为。
程序包含竞争条件,因为工作线程对变量 t
的访问与主线程对变量 t
的销毁是不同步的。解决此问题的一种方法是让主线程在退出前与每个工作线程连接(通过 pthread_join
)。
关于c++ - 使用 Pthreads 的 Hello World 内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11891492/