带有Pthreads的Hello World损坏内存

Cal*_*orm 4 c c++ pthreads segmentation-fault

我正在研究llnl.computing.gov pthreads教程中的一些简单的pthread示例.网站上的程序打印出threadid的地址,但是我想将id的地址传递给PrintHello,然后使用取消引用地址来获取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);
}
Run Code Online (Sandbox Code Playgroud)

当我在Cygwin中编译并运行它时,它会出现堆栈损坏错误.如果我将PrintHello重写为:

void *PrintHello(void *threadid)
{
  long taskid = (long) threadid;
  sleep(1);
  printf("Hello from thread %ld\n", taskid);
  pthread_exit(NULL);
 }
Run Code Online (Sandbox Code Playgroud)

它不会出错,它只是打印地址,我想取消引用地址并从main获取t的值.

有没有人对如何实现这一目标有一些指导?我知道我可以传递tpthread_create代替&t,但我想这样做,这样对学习的目的.

Jam*_*lis 9

当您pthread_exit(NULL)从主线程调用时,它会终止该线程.此时,main函数中的任何局部变量(包括t)都将被销毁,并且不能再使用.

如果主线程在所有工作线程完成之前退出t(通过您通过它传递给它们的指针pthread_create),则程序会显示未定义的行为.

该程序包含竞争条件,因为t来自工作线程的变量的访问和t来自主线程的变量的破坏是不同步的.解决此问题的一种方法是让主线程pthread_join在退出之前与每个工作线程(via )连接.