我编写了一个代码来打印字符串:使用 pthread 的“线程 0”到“线程 4”。
这是我的代码:
情况1:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function(void* parameter) {
long *i = (long *)parameter;
printf("Thread %ld\n", *i);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t threads[5];
long i = 0;
for (i = 0; i < 5; i++) {
pthread_create(&threads[i], 0, print_message_function, (void *)&i);
}
pthread_exit(NULL);
}
但结果是:
Thread 2
Thread 3
Thread 3
Thread 4
Thread 5
或者:
Thread 0
Thread 0
Thread 0
Thread 0
Thread 0
当我再次运行它时它改变了。所以我不知道为什么我传递的值是(2到5)或全部(0)或.....(很多情况下)。我认为我通过的论点是从 0 到 4。
案例二:
当我更改为新代码时:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function(void *parameter);
int main(int argc, char *argv[]) {
pthread_t threads[5];
int i = 0;
for (i = 0; i < 5; i++) {
char *msg = (char*)malloc(sizeof(char));
sprintf(msg, "Thread %d", i);
pthread_create(&threads[i], 0, print_message_function, (void *)msg);
}
}
void *print_message_function(void *parameter) {
printf("%s\n", (char *)parameter);
}
结果是:
Thread 1
Thread 0
Thread 3
Thread 2
Thread 4
Thread 4
这意味着循环运行 6 次!为什么?