gpt4 book ai didi

c - 未定义对 p_thread_create、p_thread_join 和 p_thread_exit 的引用

转载 作者:行者123 更新时间:2023-11-30 15:36:22 25 4
gpt4 key购买 nike

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

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

我正在使用 Ubuntu 13 和 Workstation 10。

我的代码:

#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

最佳答案

这段代码中有三个错误:

  1. 所有 pthread 函数都命名为 pthread_something,而不是 p_thread_something。编译器不会为您纠正此拼写错误。删除“p”后面所有出现的下划线。

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

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

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

关于c - 未定义对 p_thread_create、p_thread_join 和 p_thread_exit 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22599723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com