Home > Back-end >  : I value in multiple threads for loop
: I value in multiple threads for loop

Time:11-18

Each elder, beginners contact multithreading, recently encountered a problem in practice, speaking, reading and writing lock...

10, 8 read threads, thread 2 write threads, loop to create
Share a counter value

Read and write threads are to print the current counter, as well as dar and create a thread for loop count I
Output:


Results show where I count is all 8,
===========read
Rather than write 0 ~ 1 my imagination, and the read 0 ~ 7


To ask all of you here, this is according to, where is my code out of the problem or not considering the lack of place/knowledge?

The code below


 
# define ERROR_THREAD_CREATE (flag) STD: : cout<& lt;" Pthread create error, flag="& lt; Return flag

Int counter;
Pthread_rwlock_t rwlock;

Void * th_write (void * arg)
{
Arg int * I=(int *);

While (1)
{
Pthread_rwlock_wrlock (& amp; Rwlock);
+ + counter;
STD: : cout<& lt;">==========write "& lt; <* I & lt; & lt;" Thread: "& lt; <& lt;" Counter="& lt; //I was cycle create a thread for loop count
Pthread_rwlock_unlock (& amp; Rwlock);
Usleep (1);
}

return 0;
}

Void * th_read (void * arg)
{
Arg int * I=(int *);

While (1)
{
Pthread_rwlock_rdlock (& amp; Rwlock);
STD: : cout<& lt;">==========read "& lt; <* i<& lt;" Thread: "& lt; CodePudding user response:

Because of the last parameter pthread_create you pass in the pointer is to use variable cycle,

CodePudding user response:

Many problems, in addition to the LS said, there is also the question of variable scope

 for (int k=0; K & lt; 2; K++)//k is the local variable here, left the for loop, k be stack collected in theory, so the bottom (void *) & amp; K left for actually so illegal memory operations 
{
Res=pthread_create (& amp; Tids [k], NULL, th_write, (void *) & amp; K);//here is the address of k, so he wrote two threads used * th_write (void * arg) at the same arg
If (res)
{
ERROR_THREAD_CREATE (res);
}
}

for (int i=0; i <8; I++)//I here is also a local variable, k above the likely scenario is recycled, after I reused the k of memory space (that is, I and k at the same address), so the final 8 k and I are
{
Res=pthread_create (& amp; Tids [I + 2], NULL, th_read, (void *) & amp; I);//and k problem, here is the address of the I, eight reader thread * th_read (void * arg) at the same arg, at the same time because I repeat use of k of memory, so the two writer thread arg also into 8 (which is why the above said leave for & amp; K belong to illegal memory operations)
If (res)
{
ERROR_THREAD_CREATE (res);
}
}

  • Related