c++ - 使用 Pthreads 的 Hello World 内存损坏

标签 c++ c pthreads segmentation-fault

我正在研究 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/

相关文章:

c++ - 如何连接/合并 vector

c++ - 在存在异常的情况下使用 for_each? std::exception_list

c++ - 如何确定字符的 Unicode block ,特别是 Qt QChar?

c - 从一个函数返回多个值

c - 当我使用 N=1023 而不是 1024 时,为什么在下面的程序中会出现段错误(核心已转储)?

c++ - setDIbitstodevice Turbo C++

c - C 中的移位运算符前置一个而不是零

c - 线程缓冲区 : how to prevent racing between clients and have client and server working on buffer simultaneously

c++ - 从 C++ "time.h"测量的运行时间是实际运行时间的两倍

multithreading - pthread_create()不创建线程