【问题标题】:Undefined Reference to p_thread_create, p_thread_join and p_thread_exit [closed]未定义对 p_thread_create、p_thread_join 和 p_thread_exit 的引用 [关闭]
【发布时间】:2014-05-01 05:43:15
【问题描述】:

我目前正在学习 c 中的线程,我做了这个程序。

但是,我在编译它时遇到了麻烦。我在网上搜索了不同的编译方法,但到目前为止,它们都不适合我(尽管它对其他人有用),我不知道为什么......

我正在使用带有 Workstation 10 的 Ubuntu 13。

我的代码:

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

typedef struct node {
    int i;
    int j;
} NODE;

void merge(int i, int j);
void * mergesort(void *x);

int x[] = {7, 12, 19, 3, 18, 4, 2, 6, 15, 8};

int main() {
    int i;
    NODE m;
    m.i = 0;
    m.j = 9;
    pthread_t tid;

    int check;

    check = p_thread_create(&tid, NULL, mergesort, &m);

    if (check) {
        printf("Unable to create thread %d\n", check);
        exit(1);
    }

    pthread_join(tid, NULL);

    for (i = 0; i < 10; i++) {
        printf("%d \n", x[i]);
    }

    return 0;
}

void merge(int i, int j) {
    int middle = (i+j)/2;
    int xi = i;
    int yi = middle+1;

    int newx[j-i+1], newxi = 0;

    while(xi <= middle && yi <= j) {
        if (x[xi] > x[yi]) {
            newx[newxi++] = x[yi++];
        }
        else {
            newx[newxi++] = x[xi++];
        }
    }

    while (xi <= middle) {
        newx[newxi++] = x[xi++];
    }

    while (yi <= j) {
        newx[newxi++] = x[yi++];
    }

    for (xi = 0; xi < (j-i+1); xi++) {
        x[i+xi] = newx[xi];
    }
}

void * mergesort(void *x) {
    NODE *p = (NODE *)x;
    NODE n1, n2;
    int middle = (p->i+p->j)/2;
    pthread_t tid1, tid2;
    int ret;

    n1.i = p->i;
    n1.j = middle;

    n2.i = middle+1;
    n2.j = p->j;

    if (p->i >= p->j) {
        return;
    }

    int check;

    check = pthread_create(&tid1, NULL, mergesort, &n1);

    if (check) {
        printf("Unable to create thread %d\n", check);
        exit(1);
    }

    check = pthread_create(&tid2, NULL, mergesort, &n2);

    if (check) {
        printf("Unable to create thread %d\n", check);
        exit(1);
    }

    p_thread_join(tid1, NULL);
    p_thread_join(tid2, NULL);

    merge(p->i, p->j);
    p_thread_exit(NULL);
}

到目前为止我所尝试的:

gcc -pthread thread.c
gcc thread.c -pthread
gcc -lpthread thread.c
gcc thread.c -lpthread
gcc -o thread thread.c -pthread
gcc -o thread thread.c -lpthread
gcc -pthread -o thread thread.c
gcc -lpthread -o thread thread.c

【问题讨论】:

  • 哦.. 我没注意到。谢谢!
  • 你需要训练自己看清这样的单字错误。但不要为此感到太难过;我有多年的经验,但有时我仍然会想念他们。

标签: c multithreading gcc pthreads


【解决方案1】:

这段代码有三个错误:

  1. 所有 pthreads 函数都命名为 pthread_something,而不是 p_thread_something。编译器不会为您更正这个错字。删除所有出现的“p”后面的下划线。

  2. 至少在某些(BSD 派生的?)系统上,stdlib.h 声明了一个名为 mergesort 且签名不兼容的函数,因此您需要重命名它。

  3. mergesort 函数中有一个没有值的 return 语句,它被声明为返回 void *。那需要改成return 0;

当我进行这三个更改时,您的程序可以工作,或者无论如何它似乎可以工作(它应该打印一个排序的数字列表,是吗?)

【讨论】:

  • 我明白了,是的,它应该打印一个排序的数字列表。谢谢,我现在明白了!
猜你喜欢
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多