Topic: C Problem with Threads (Page 1 of 1) Pages that link to <a href="https://ozoneasylum.com/backlink?for=28428" title="Pages that link to Topic: C Problem with Threads (Page 1 of 1)" rel="nofollow" >Topic: C Problem with Threads <span class="small">(Page 1 of 1)</span>\

 
Moon Shadow
Paranoid (IV) Inmate

From: Paris, France
Insane since: Jan 2003

posted posted 09-14-2006 02:21

Hi,

First of all, I didn't know where to post this topic, so please move it if needed. The Asylum may not be the best place to post this kind of topic but I guess there are good programmers lurking around that may be able to help me

So basically, in several programs I have to start a new Thread from my main function. Then, later in the program, I sometimes have to close the main function first and close the Thread I created after the main function. The problem is that the program is not closed 'properly', it doesn't do anything anymore and doesn't give me back the prompt.

Which is quite embarassing

Below is a part of the source code of one of the programs having this problem. Basically what I do is :

- declare all the variables needed to start a new thread
- initialize them
- create the new thread - in this example, the argument handle_copy is the handle of the main thread (needed to close the main function later)

The main function then does some things, as long as it is not stopped by the sub function.
The sub function executes some instructions too, then terminates the main function, and finally does some other things and closes itself.

Forgive the comments in French,it's late here and I'm too tired to rewrite them in English.

code:
#include <windows.h>
#include <stdio.h>
#include <conio.h>

DWORD trace_test_err(LPCTSTR position, DWORD numero, BOOL trace, DWORD ignore_error, BOOL stop);
DWORD WINAPI thread_bad(HANDLE handle_main);

/*************************************************************************/
/*			main function
/*************************************************************************/

int main (void)
{

    /* initialisation des paramètres de l'unité d'exécution secondaire */
    HANDLE handle_thread;                                                        /* handle sur l'objets du noyau thread */
    SECURITY_ATTRIBUTES sa;						/* attribut de sécurité */
    DWORD dwStackSize;							/* taille de la pile pour l'unité d'exécution */
    LPTHREAD_START_ROUTINE lpStartAdress;	          	 /* pointeur sur la fonction unité d'exécution */
    DWORD dwCreationFlags;						         /* flag de création pour l'unité d'exécution */
    DWORD lpThreadId;							         /* identification de l'unité d'exécution */				

    lpStartAdress = thread_bad;					         /* fonction à lancer comme thread */
    dwStackSize = 0;							         /* taille de la pile par défaut : 1mo */
    dwCreationFlags = 0;               			                           /* création en mode normal */
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);	                  /* taille de la structure */
    sa.lpSecurityDescriptor = NULL;				         /* sécurité par défaut */
    sa.bInheritHandle = FALSE;					         /* handle non héritable */

    HANDLE handle_current_process = GetCurrentProcess();   /* récupération d'un pseudo handle pour le process en cours */
    HANDLE handle_current_thread = GetCurrentThread();      /* récupération d'un pseudo handle pour la tâche en cours */
    HANDLE handle_copy;                                                           /* handle qui recevra le handle dupliqué */

    if ( ! (DuplicateHandle(handle_current_process, handle_current_thread, handle_current_process, &handle_copy, 0, FALSE, DUPLICATE_SAME_ACCESS)) )
        trace_test_err("DuplicateThread", 0, TRUE, 0, TRUE);

    if ( ! (handle_thread = CreateThread(&sa, dwStackSize, lpStartAdress, handle_copy, dwCreationFlags, &lpThreadId)))
	   	trace_test_err("CreateThread", 0, TRUE, 0, TRUE);

    // do some things
    
    ExitThread(0);

}

/*************************************************************************/
/*			sub function
/*************************************************************************/

DWORD WINAPI thread_bad(HANDLE handle_main)
{

    // do some things
    
    if ( ! TerminateThread(handle_main, 0) )
        trace_test_err("TerminateThread", 0, TRUE, 0, TRUE);
        
    // do some other things
    
   ExitThread(0);

}



At the beginning, both Threads run at the same time perfectly. Then the sub function terminates the main function, and then closes itself. The problem is, everything seems to work fine (both threads indeed stop what they were doing) except that I'm not going back to the prompt.

I've tried return 0 instead of ExitThread(0) but it didn't change anything.

Anyone knows what I am doing wrong ?

----
If wishes were fishes, we'd all cast nets.



(Edited by Moon Shadow on 09-14-2006 02:32)

(Edited by Moon Shadow on 09-14-2006 02:34)

Tyberius Prime
Maniac (V) Mad Scientist with Finglongers

From: Germany
Insane since: Sep 2001

posted posted 09-14-2006 10:46

I don't get your 'TerminateThread ( handle_main...)' - what's that supossed to do?

Usually, you'd signal your threads(via a semaphore, a shared global bool, whatever) to skip the rest of their workload,
and then you'd rejoin them. I believe that would be done with WaitForSingleObject on the thread handle in plain old win32 - but
I'm not sure.

Anyhow, waiting for your threads to terminate ( and getting them to abandon their work ) is the key here.
And if your '//do some other things' ain't a loop, you'll have to do the check before each time consuming step to get good response times.

so long,

->Tyberius Prime

Moon Shadow
Paranoid (IV) Inmate

From: Paris, France
Insane since: Jan 2003

posted posted 09-14-2006 14:58

I did not know what really were semaphores when I posted, but since you mentionned them I read some articles about the topic... And indeed using an event semaphore or a mutex semaphore along with WaitForSingleObject seems to be the way to go for the kind of things I had in mind.

I'll look into that and let you know if I still have problems I can't solve.

Again, many thanks for the help TP

----
If wishes were fishes, we'd all cast nets.



Post Reply
 
Your User Name:
Your Password:
Login Options:
 
Your Text:
Loading...
Options:


« BackwardsOnwards »

Show Forum Drop Down Menu