pthread参数的值已更改 [英] pthread argument's value changed
问题描述
这是我的主要功能,其中 NO_RECIEVERS = 3
.我正在尝试使用我发送的 i
的值来区分编写者线程和读取者线程.
This is my main function, where NO_RECIEVERS = 3
. I am trying to differentiate between the writer and reader threads using the value of i
that i send.
int main() {
int status, i;
pthread_t tr[NO_RECIEVERS], tw[NO_SENDERS], bd;
i=1;
for(i=1; i<=NO_SENDERS; i++) {
pthread_create(&tw[i-1], NULL, writer, &i);
}
for(i=1; i<=NO_RECIEVERS; i++) {
printf("%d\n", i);
pthread_create(&tr[i-1], NULL, reader, &i);
}
pthread_create(&bd, NULL ,daemon_thread, NULL);
for(i=1; i<=NO_SENDERS; i++) {
pthread_join(tw[i-1], NULL);
}
for(i=1; i<=NO_RECIEVERS; i++) {
pthread_join(tr[i-1], NULL);
}
pthread_join(bd, NULL);
return 0;
}
我的阅读器功能如下
void* reader(void *val) {
int ret, fd, id;
struct mssg data;
id = *(int*)val;
printf("id: %d %d\n", id, *(int*)val);
while(1) {
但是此函数似乎正在创建ID为一些随机值的线程..我得到了这样的日志
But this function seems to be creating threads with id some random values.. i get a log like this
...
id: 1 1
...
id: 2 2
...
id: 1 1
下次我得到..它是随机的
Next time i get.. its kind of random
...
id: 1 1
...
2
id: 2 2
...
id: 4 4
但是我分配的值仅限于1,2,3
But the values i am assigning are limited to 1,2,3
推荐答案
您将& i
传递给了您创建的所有线程...因此,每个线程都有一个指向 i
,然后当他们取消引用以读取 i
的值时,所读取的就是当时的 i
.
You passed &i
to all the threads you created... so each one has a pointer to i
, and when they dereference that to read the value of i
, and what they read is whatever i
happens to be at the time.
如果要在 pthread_create
时传递 i
的值,我建议 malloc()
占用一小段内存,将 i
复制到其中,然后将已分配的内容传递给线程(线程可以读取该内容,并可以将 free()
传递给内存.)或其他任何提供<为创建的每个线程在不同位置放置code> i .
If you want to pass the value of i
at the time of the pthread_create
, I suggest malloc()
a small piece of memory, copy i
to it and pass the malloced thing to the thread (which can read it and the free()
the memory. Or any other method that provides a copy of i
in a different location for each thread created.
这篇关于pthread参数的值已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!