标签: pthread-join

pthread_exit发出返回结构

我有一个结构

typedef struct something_t {
    int a;
    int b;
} VALUES;
Run Code Online (Sandbox Code Playgroud)

在我的线程函数中我做

VALUES values;
values.a = 10;
values.b = 11;

pthread_exit((void*)&values);
Run Code Online (Sandbox Code Playgroud)

我试着通过这样做来接受

VALUES values;
pthread_join(thread, (void*)&values);
printf("A: %d\B: %d\n", values.a, values.b);
Run Code Online (Sandbox Code Playgroud)

我收到的价值每次都很奇怪.我很困惑如何接收我最终在线程中创建的值.我试图在C中学习线程,似乎我已经掌握了它,但我无法返回值.有办法吗?感谢任何人的帮助.

c multithreading pthreads pthread-join

0
推荐指数
1
解决办法
2390
查看次数

pthread_join导致分段错误(简单程序)

我只是尝试使用多线程程序,但我遇到了pthread_join函数的问题.下面的代码只是一个我用来显示pthread_join崩溃的简单程序.此代码的输出将是:

before create

child thread

after create

Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

什么原因导致pthread_join给出分段错误?

#include <pthread.h>
#include <stdio.h>

void * dostuff() {
    printf("child thread\n");
    return NULL;
}

int main() {
    pthread_t p1;

    printf("before create\n");
    pthread_create(&p1, NULL, dostuff(), NULL);
    printf("after create\n");

    pthread_join(p1, NULL);
    printf("joined\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c multithreading pthreads segmentation-fault pthread-join

0
推荐指数
2
解决办法
5181
查看次数

为什么pthread_join在上一次迭代中失败(给出分段错误)?

多线程初学者在这里。恰好在第5次迭代(即执行pthread_join(threadID [4],NULL)时),我的程序由于分段错误而失败。

我正在创建多个线程以从计数器变量中加减1以研究竞争条件。一切正常,直到我尝试5个线程或更多。恰好在pthread_join(threadID [4],NULL)的最后一次迭代中,它失败了,我无法确定原因。我确定问题出在哪里,因为我使用printf语句查看失败之前到达的位置。

#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdint.h>
#include <errno.h>
#include <string.h>
#include <getopt.h>
#include <time.h>

int opt_threads;
int opt_iterations;
long nThreads;
long nIterations;
int opt_yield;
long long counter;

void add(long long *pointer, long long value) {
  long long sum = *pointer + value;
  if (opt_yield)
    sched_yield();
  *pointer = sum;
}

void *thread_worker(void * arg) {
  long i;
  for (i=0; i<nIterations; i++) {
    add(&counter, 1);
    add(&counter, -1);
  }

  return arg; …
Run Code Online (Sandbox Code Playgroud)

c multithreading pthreads pthread-join

0
推荐指数
1
解决办法
48
查看次数

以下程序的输出

当我运行以下程序时,输出为5.
为什么5?为什么不是8?

void *doit(void *vargp) {
    int i = 3;
    int *ptr = (int*)vargp;
    (*ptr)++;
}
int main() {
    int i = 0;
    pthread_t tid;
    pthread_create(&tid, NULL, doit, (void*)&i);
    pthread_join(tid,NULL);
    i = i + 4;
    printf("%d",i);
}
Run Code Online (Sandbox Code Playgroud)

c pthreads pthread-join

-2
推荐指数
1
解决办法
90
查看次数