|
Thread problem |
DailyDose
Member #15,528
March 2014
|
Hello, I've been learning about threads recently and tried to make a function that would create and return a thread given an instance of a class where there are the cond, the mutex, and the variables for my thread. The problem is when creating one thread with this function, the program either crashes immediately after running or runs smoothly but then crashes on close. And when I try to create two threads with it it seems to be stuck in the following loop, I've tried changing many things in my code but to no avail and tried to look around but not much luck either there. So here is the code in my thread.cpp file excluding headers, etc: 1void *Func_Thread(ALLEGRO_THREAD *thr, void *arg){
2
3 DATA *data = (DATA*) arg;
4 float num = 0.1;
5 int i = 0;
6
7 al_lock_mutex(data->mutex);
8 bool a_bool = data->a_bool;
9 bool b_bool = data->b_bool;
10 bool c_bool = data->c_bool;
11 bool d_bool = data->d_bool;
12 bool e_bool = data->e_bool;
13 data->ready = true;
14 al_broadcast_cond(data->cond);
15 al_unlock_mutex(data->mutex);
16
17 while(!al_get_thread_should_stop(thr)){
18
19 al_lock_mutex(data->mutex);
20
21 if(a_bool){
22
23 }
24
25 if(b_bool){
26
27 }
28
29 if(c_bool){
30
31 }
32
33 if(d_bool){
34
35 }
36
37 if(e_bool){
38
39 }
40
41 al_unlock_mutex(data->mutex);
42
43 al_rest(thread_delay);
44
45 }
46
47
48 return NULL;
49}
50
51ALLEGRO_THREAD* create_thread(DATA data, bool a, bool b, bool c, bool d, bool e, int thread_number){
52
53 ALLEGRO_THREAD* thread_o = NULL;
54 thread_o = al_create_thread(Func_Thread, &data);
55 al_start_thread(thread_o);
56 al_lock_mutex(data.mutex);
57 while(!data.ready){
58 al_wait_cond(data.cond, data.mutex);
59 }
60 al_unlock_mutex(data.mutex);
61
62 al_lock_mutex(data.mutex);
63 data.a_bool = a;
64 data.b_bool = b;
65 data.c_bool = c;
66 data.d_bool = d;
67 data.e_bool = e;
68 data.ready = false;
69 al_unlock_mutex(data.mutex);
70
71 return thread_o;
72
73}
The class I'm using is the same as the one from the tutorial but with more bools. In the main code I have this: 1DATA data;
2
3ALLEGRO_THREAD* thread_1 = NULL;
4thread_1 = create_thread(data, true, false, false, false, false, 0)
Thanks for the read, |
someone972
Member #7,719
August 2006
|
Probably the main problem is that you are passing a copy of the DATA object in your create_thread function. This means the address that is being passed to the Func_Thread actually points to the copy on the stack from the create_thread, which is destroyed as soon as create_thread exits. You should instead pass in a pointer to the data object. ______________________________________ |
DailyDose
Member #15,528
March 2014
|
Thanks for the reply, it fixed the problem in less than 5 minutes. |
|