【发布时间】: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