我正在使用pthread_create和mutexes使用線程,但我注意到在我的簡單示例中,存儲在傳遞給pthread_create的結構中的int值在線程執行方法時不保留其值SimpleThread。以下是代碼。具體來說,在第63行中,我將循環中的count指定給用作pthread_create中參數的struct線程中的int id。在第22行中,我從結構中打印出id的值,它總是給出相同的值。如果我創建2個線程,則值爲2.如果我創建3個線程,則值爲3.該模式將繼續。我想我只是好奇,爲什麼發生這種情況得到實際的價值,而不是我喜歡我打算線63傳入pthread_create的值已更改
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4 #include <unistd.h>
5
6 #define PROGRAM_NAME 0
7 #define NUM_THREADS 1
8
9 int SharedVariable;
10 pthread_mutex_t mutex;
11
12 struct thread
13 {
14 pthread_t t;
15 int id;
16 };
17
18 void* SimpleThread(void* arg)
19 {
20 struct thread* parameter = (struct thread*) arg;
21 int which = parameter->id;
22 printf("Threads IDs in SimpleThread -- %d\n", parameter->id);
23
24 pthread_mutex_lock(&mutex);
25
26 int num, val;
27
28 for(num = 0; num < 20; num++)
29 {
30 if(random() > RAND_MAX/2)
31 usleep(10);
32
33 val = SharedVariable;
34
35 //printf("***thread %d sees value %d\n", which, val);
36 SharedVariable = val + 1;
37 }
38
39 val = SharedVariable;
40 //printf("Thread %d sees final value %d\n", which, val);
41
42 pthread_mutex_unlock(&mutex);
43
44 return (void *) arg;
45 }
46
47 int main(int argc, char* argv[ ])
48 {
49 int num_threads, i;
50
51 if(argc != 2)
52 {
53 fprintf(stderr, "Usage: %s <num_threads>\n", argv[ PROGRAM_NAME ]);
54 return -1;
55 }
56 num_threads = atoi(argv[ NUM_THREADS ]);
57 struct thread* container = (struct thread*) malloc(num_threads * sizeof(struct thread));
58
59 pthread_mutex_init(&mutex, NULL);
60
61 for(i = 0; i < num_threads; i++)
62 {
63 container[ i ].id = i;
64 pthread_create(&container[ i ].t, 0, SimpleThread, &container);
65 }
66
67 for(i = 0; i < num_threads; i++)
68 {
69 pthread_join(container[ i ].t, 0);
70 }
71
72 pthread_mutex_destroy(&mutex);
73
74 return 0;
75 }
'結構螺紋*參數=(結構螺紋*)ARG;',然後'結構螺紋*容器=(結構螺紋* )malloc' - *** AAAAAAAAARRRRRGGGGHHHH!*** – 2013-06-30 20:16:42
不要投malloc也。 –
我試圖刪除malloc,但輸出後出現分段錯誤。這是我的理解,主函數中的malloc初始化結構,然後我使用初始化的結構作爲SimpleThread函數中的參數。 – wmarquez