分段错误你能解释为什么在Linux中(而不是在苹果机)我得到段错误,当我做:更改顺序将返回在Linux上
pthread_join(thread2, (void**)&status);
pthread_join(thread1, (void**)&status);
不过是确定的,当我做:
pthread_join(thread1, (void**)&status);
pthread_join(thread2, (void**)&status);
我想在Mac上,一切都很好,但在Linux的代码运行正常只有当我的加入线程1的,之后的加入的线程2 ...
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_msg(char *ptr);
main(){
pthread_t thread1, thread2;
char *message1 = "Ping";
char *message2 = "Pong";
int status;
pthread_create(&thread1, NULL, print_msg, message1);
printf("tid thread1= %d\n", (int)thread1);
pthread_create(&thread2, NULL, print_msg, message2);
printf("tid thread2= %d\n", (int)thread2);
pthread_join(thread2, (void**)&status);
pthread_join(thread1, (void**)&status);
printf("Thread 1 end with: %d\n", (int)status);
printf("Thread 2 end with: %d\n", (int)status);
exit(0);
}
void *print_msg(char *ptr){
char *msg;
void *val=0;
msg = (char *) ptr;
printf("%s \n", msg);
pthread_exit(val);
}
您可能想要先修复所有编译器警告,有几个。你可以用'-Wall'和'-Wextra'编译你的代码,这会告诉你很多潜在的错误。你也可以读作[并行线程DOC(http://man7.org/linux/man-pages/man3/pthread_create.3.html),其中包含例如如何使用'在pthread_join()' – SSC