c - 使用线程的未知错误

标签 c multithreading ubuntu pthreads

我在使用这段代码时遇到了问题,这是我书中的基本代码,可帮助理解线程的工作原理。它应该创建 NTHREADS,它应该执行 neg 函数,然后返回接收到的参数的反面

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>

#define NTHREADS 2

void *neg (void * param);

int main(int argc, char * argv[]){

    pthread_t threads[NTHREADS];
    int arg [NTHREADS];
    int err;

    long i;
    for(i = 0; i< NTHREADS; i++){
        arg[i] = i;
        err= pthread_create(&(threads[i]), NULL, &neg, (void *) &(arg[i]));

        if(err =! 0){
        error(err,"pthread_create");
        }
    }

    int j;
    for (j = 0; j < NTHREADS; j++){
        int *r;
        err= pthread_join(threads[j], (void **) &r);
        printf("Resultat [%d] = %d \n", j, *r);

        free(r);
        if(err!=0){
        error(err,"pthread_join");
        }
    }
return(EXIT_SUCCESS);
}

void *neg (void * param){
    int *l;
    l= (int *) param;
    int *r= (int *) malloc(sizeof(int));
    *r = -*l;
    return ((void *) r);
}

编译时我收到此消息:

nico@nico-G56JR:~/Desktop$ gcc -pthread Threads.c
nico@nico-G56JR:~/Desktop$ ./a.out
./a.out: c: Unknown error 4196644

我找不到错误,有人可以帮我吗?

提前致谢

最佳答案

这个

 if(err =! 0){

应该是

 if(err != 0){

真的有点倒霉,因为err =! 0 实际上编译,为 err 分配一个非零值,然后属于错误情况,将一些对您的代码没有真正意义的东西传递给错误函数。

关于c - 使用线程的未知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25287049/

相关文章:

C 代码-If 条件 HW

java - Android Studio错误: "Method getText() must be called from the UI Thread,当前推断线程是worker

java - 垃圾收集和同步可见性

php - 为什么这个进程不在后台运行?

ubuntu - 我需要做什么才能使用存储库中的 ruby​​-full 包在 ubuntu 10.04 上运行 ruby​​-debug19?

ubuntu - 示例 nginx Dockerfile 有问题

c - ANSI C : Passing array by value generates weird error I can not solve

c - C源文件包含自己的头文件有什么好处

c - 在 C 中查找连续整数的问题

java - 线程死锁