#### Archived

This topic is now archived and is closed to further replies.

# Multi Threads... just a simple example plz...

This topic is 5793 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I''ve looked around and found quite a lot on threads but they are so intertwined with other garbage I cant make heads or tails of it... I tried looking on MSDN but had to give up before I died of dehydration. (Should pin a note on my monitor stating I need supplies before venturing into the labyrinth that is MSDN) So if some one could kindly explain how a thread is formed I would be grateful. Thank you. btw its for a MFC dialog app... if that changes anything... but I purely want to know how to assign a class object to its own thread. thanks. crakinshot

##### Share on other sites

MSDN says not to use CreateThread() when you are using the C run times because it creates memory leaks...... And even if you are not, just to be safe, stick to _beginthreadex(), its used the exact same way as CreateThread().

Its not so complicated, you just need to fill in a couple options, pass a function pointer, the thread starts.. And to end it you call _endthreadex() from within the thread... They have some code samples on MSDN.

##### Share on other sites
If you''re using MFC, you''ll either want to use ClassWizard to create your own CWinThread-derived class, or use AfxBeginThread. If you''re not using MFC, do as Max_Payne said.

CMyWinThread* p = new CMyWinThread;p->m_bAutoDelete = true; // not sure if this is set automatically to truep->CreateThread();

UINT MyThread(LPVOID param){  // do stuff  return 0;}LPVOID param = 0;AfxBeginThread(MyThread, param);

##### Share on other sites
cool thx mutex

[edited by - crakinshot on September 10, 2002 3:18:39 PM]

##### Share on other sites
quote:
Original post by Max_Payne
You can just return from the thread function to end the thread.

Ending a thread from another thread is potentially unsafe, as you might kill it while it''s doing stuff, and thus prevent it from releasing stuff it''s using.

##### Share on other sites

  /* createthreadex.h */#ifndef CREATETHREADEX_H_#define CREATETHREADEX_H_#pragma once#include <process.h>/* ---------------------------------------------------------------------------Q132078: "How to Use _beginthreadex() and _endthreadex()"http://support.microsoft.com/default.aspx?scid=KB;EN-US;q132078&    When developing a multithreaded Win32-based application with Visual C++,    you need to use the CRT thread functions to create any threads that call    CRT functions. To create and terminate threads, use either _beginthread()    and _endthread() or _beginthreadex() and _endthreadex().    If you use the Win32 APIs CreateThread() and ExitThread() instead,    some of the CRT functions used in the thread will not work.    You need to use the CRT functions to both create and end the threads    or you lose the memory that the CRT allocates for the thread.    In addition to preventing memory leaks, using _beginthreadex places    a structured exception handling frame around the thread function    so that the signal function and floating point exceptions work correctly.See also:Win32 Q&A, MSJ July 1999http://www.microsoft.com/msj/0799/win32/win320799.htmWin32 Q&A, MSJ October 1999http://www.microsoft.com/msj/1099/win32/win321099.htmHere are two macro overlays to facilatate this usage:Note:The thread that uses CreateThreadEx to launch new threads shouldalso dispose of any generated thread handle using CloseHandle.    HANDLE MyThread = CreateThreadEx(...);    ...    CloseHandle(MyThread);--------------------------------------------------------------------------- */typedef unsigned (__stdcall *StartAddressT)(void*);#define CreateThreadEx(                         \    lpThreadAttributes,                         \    dwStackSize,                                \    lpStartAddress,                             \    lpParameter,                                \    dwCreationFlags,                            \    lpThreadId                                  \)                                               \ ( (HANDLE) _beginthreadex(                     \	    (void *)        (lpThreadAttributes),   \    	(unsigned int)  (dwStackSize),          \	    (StartAddressT) (lpStartAddress),       \    	(void *)        (lpParameter),          \	    (unsigned int)  (dwCreationFlags),      \    	(unsigned int *) (lpThreadId) ) )#define ExitThreadEx(dwExitCode) _endthreadex((unsigned int)dwExitCode)#endif /* CREATETHREADEX_H_ */

##### Share on other sites
thanks guys for the help...

its ovois I''ll have to alter the structer of my code to incorperate this... which is annoying cus its working like a charm (except for the freezing... hehe)

anyway thanks;

ps. is there any danger of using the same objects in memory in two different threads? I know deleting objects would be futile with two threads running... but is there a problem with just accessing data?

and you want to return a class object back to the calling item. would this have to be done before I close the thread (or just returning 0); or after? my main concern is if I create an object while in a thread then close the thread the data is deleted along with the thread??...

##### Share on other sites
quote:
ps. is there any danger of using the same objects in memory in two different threads? I know deleting objects would be futile with two threads running... but is there a problem with just accessing data?

If no threads can change the data in any way, you do not need to synchronize access to the data.

If even one thread can modify the data in any way, you do need to synchronize accesso to the data.

To synchronize a thread, you create a CRITICAL_SECTION object that can be shared between all threads. When a thread is about to access the data, it must call EnterCriticalSection first, and then it must call LeaveCriticalSection after it has finished with the data. The CRITICAL_SECTION object ensures that only one thread gets access to the data at a time, and that each thread''s accesses are performed atomically (that is, all-at-once without interruption by other threads).

I think that MFC has a class that wraps up this CRITICAL_SECTION stuff for you.

##### Share on other sites
quote:
and you want to return a class object back to the calling item. would this have to be done before I close the thread (or just returning 0); or after? my main concern is if I create an object while in a thread then close the thread the data is deleted along with the thread??...

No, all threads share the process''s memory space, so they also share the process''s free store. You can freely create an object in one thread and delete it in another.

##### Share on other sites
quote:
Original post by null_pointer
I think that MFC has a class that wraps up this CRITICAL_SECTION stuff for you.
Indeed it does:
CCriticalSection g_cs;CString g_sData;  // data that requires synchronizationUINT ThreadOne(LPVOID param){  g_cs.Lock();  sData = "Blah";  g_cs.Unlock();  return 0;}UINT ThreadTwo(LPVOID param){  g_cs.Lock();  sData = "Asdf";  g_cs.Unlock();  return 0;}

Thread synchronization is absolutely crucial. Any data modification or access needs to be synchronized. If not, your program will leak memory, crash, and do bad things to furry hamsters.

If it''s hard to imagine why such things would happen, just remember that two threads have the potential to execute simultaneously; the functions may run at the exact same time. What this means is that each line of code may be running simultaneously, not just entire blocks. Now try imagining your algorithm running twice at the same time to see if there are any problems.

P.S. It isn''t really truly simultaneous execution unless you have an SMP system, but I''ll leave that for someone else to explain

1. 1
2. 2
3. 3
Rutin
19
4. 4
5. 5

• 10
• 14
• 30
• 13
• 11
• ### Forum Statistics

• Total Topics
631785
• Total Posts
3002348
×