繁体   English   中英

传递给pthread_create的值已更改

[英]Value passed into pthread_create changed

我当时正在使用pthread_create和互斥锁来处理线程,但是我注意到在我的简单示例中,当线程执行方法SimpleThread时,存储在传递给pthread_create的结构中的int值不会保留其值。 下面是代码。 具体来说,在第63行中,我将循环的计数分配给struct线程中的int id(用作pthread_create中的参数)。 在第22行中,我从结构中打印出id的值,它总是给出相同的值。 如果创建2个线程,则值为2。如果创建3个线程,则值为3。模式将继续。 我想我很好奇为什么会发生这种情况,而不是像第63行中那样获得i的实际值。

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   }

您没有将正确的数组元素传递到线程中。

代替

pthread_create( &container[ i ].t, 0, SimpleThread, &container )

你需要这样做

pthread_create( &container[ i ].t, 0, SimpleThread, &container[i] )

您将相同的地址分配给2个不同的线程作为参数。 您可以通过这种方式使其成为共享资源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM