pthread 中的参数传递错误 [英] Arguments were passed wrong in pthread
问题描述
我编写了一个代码来打印字符串:Thread 0";到线程 4"使用 pthread.
I write a code to print out strings: "Thread 0" to "Thread 4" using pthread.
这是我的代码:
#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.
It changed when I run it again. So I don't know why the values I passed are (2 to 5) or all (0) or ..... (many cases). I think my arguments I passed is from 0 to 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 次!为什么?
It means the loop run 6 times! Why?
推荐答案
将案例 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);
}
您之前看到不一致结果的原因是因为您将一个指针传递给每个线程,其中每个指针都指向同一个局部变量,然后您正在修改该变量.
The reason that you were seeing inconsistent results before was because you were passing a pointer to each thread where each pointer was pointing at the same local variable, which you were then modifying.
在情况 2 中,您仅 malloc
处理单个字符,然后尝试向其中写入字符串.应该很容易修复.
In Case 2 you are malloc
ing only a single char and then trying to write a string to it. It should be fairly easy to fix.
这篇关于pthread 中的参数传递错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!