Thread with lambda function

Hi , i'm trying to realize a simple code with thread and lambda function.

My goal is to swap 2 variable .
I launch 2 thread,
The first:
Put his value in a shared variable and notify it .
wait until an event on a condition variable occur.
read from shared value .


The second wait until an event on a condition variable occur.
Wake up
read from shared value .
Put his value in a shared variable and notify it.



This is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 thread t1([&p1]()->void{
		 m.lock();
		 nt++;
		  
		 if(nt==1)  {
		 //first thread 
	     unique_lock<mutex> u1(m); ***
		 cv.wait(u1);
		 int tmp=dato;
		 p1=tmp;
		 dato=p1;
	     cv.notify_one();
	 	 
		 }else {
		 //second thread
			 
		unique_lock<mutex> u0(m);
		dato=p1;
		cv.notify_one();
 
		cv.wait(u0);
		 
		int tmp=dato;
		p1=tmp;
		dato=p1;
		  
	 }
	 
	 }	
	 );


Why it say error "abort() has been called " on the istr ***
Thanks in advance
Guessing what the rest of the code might look like (you really need to post compilable code for someone else to debug it), I believe what you have here is an uncaught exception thrown by unique_lock's constructor, which you're attempting to construct with an already-locked mutex m.

Last edited on
you'are right! Thanks :)


Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 thread t1([&p1]()->void{
 unique_lock<mutex> u1(m); 
	 
		 nt++;
		  
		 if(nt==1)  {
		 //first thread 
	    
		 cv.wait(u1);
		 int tmp=dato;
                 dato=p1;
		 p1=tmp;
		 
	     cv.notify_one();
	 	 
		 }else {
		 //second thread
			 
		 
		dato=p1;
		cv.notify_one(); 
		cv.wait(u1);
		 
		int tmp=dato;
                dato=p1;
		p1=tmp;
		
		  
	 }
	 
	 }	
	 );
Topic archived. No new replies allowed.