Solved

Threads

Posted on 2004-09-02
18
378 Views
Last Modified: 2010-04-01
Hi,

I'm having a bit of trouble with this whole threads thing, how do I get them to work?
Sample code? Tutorial web sites? Any thing that will help me!

Thnx, it's appreciated!

Jonny K
0
Comment
Question by:jonnykeogh
18 Comments
 
LVL 13

Expert Comment

by:SteH
ID: 11962126
0
 
LVL 3

Expert Comment

by:rsanwatsarkar
ID: 11962396
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 11962499
You have some good suggestions above.  Here is some sample code for Windows that hopefully will clear things up, along with an explanation of what it is doing.

Basically this program has one thread updating values in a global array and the main thread outputting the contents of the array.  If the main thread interrupts the worker thread before it has finished updating *all* of the elements in the array, then the main thread will output values that are not all the same (obviously).  
However the use of the CS ensures that the worker thread finishes updating all of the elements in the array *before* the main thread can output them.

Although it uses beginthread, you can easily modify it to use beginthreadex.  Just look up the parameters on MSDN.

#include <windows.h>
#include <process.h>
#include <stdio.h>

CRITICAL_SECTION cs;

int a[5];

void Thread(void* pParams)
{
     int i, num = 0;
     
    while (1) {
          EnterCriticalSection( &cs );
          printf("In the thread process, num is %i\n", num);
          for (i = 0; i < 5; i++) {
               a[i] = num;
          }
          num++;
          LeaveCriticalSection( &cs );
         
    }
}

int main(void)
{
     InitializeCriticalSection( &cs );

     _beginthread(Thread, 0, NULL);
     while(1) {
          EnterCriticalSection( &cs );
          printf("In the main process\n");
        printf("%d %d %d %d %d\n",  a[0], a[1], a[2], a[3], a[4] );
        LeaveCriticalSection( &cs );
     }
     return 0;
}

Hope this helps.
0
 
LVL 2

Author Comment

by:jonnykeogh
ID: 11962916
I'll just take the time now to point out that im using Borland C++ 5.0. Sorry for being a pain if I have.
0
 
LVL 2

Author Comment

by:jonnykeogh
ID: 11962938
Oh and also, I'm only a beginner at the whole C++ thing as well- havent used it in ages and don't know much advanced stuff.
0
 
LVL 13

Expert Comment

by:SteH
ID: 11963006
In BCB it is creating a TThread object instead of CWinThread. Your code goes into Execute method. Instead of the use of critical sections you can call functions from the main thread using Synchronize (function). Synchronization is done internally inside VCL.
0
 
LVL 13

Expert Comment

by:SteH
ID: 11963024
Perhaps you can ask moderators (in Community support) to move this Q to "C++ builder" Topic Area (TA) to get all Builder experts aware of this Q. Or post a Q worth 20 points in there linking to this Q. That link Q you should be able to delete as long as no one post a comment to it.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 2

Author Comment

by:jonnykeogh
ID: 11963049
!!Major problem- it brings up 'Undefined function _beginthread'!!
0
 
LVL 2

Author Comment

by:jonnykeogh
ID: 11963076
Messages I get from the 'Messages' dialog box:

Info :Compiling E:\Documents and Settings\Jonathon Keogh\Desktop\Threads\threadtest.cpp
Warn :threadtest.cpp(24,2):Parameter 'pParams' is never used
Error:threadtest.cpp(30,19):Call to undefined function '_beginthread'
Warn :threadtest.cpp(37,12):Unreachable code

^^ Messages I get ^^
0
 
LVL 2

Author Comment

by:jonnykeogh
ID: 11963084
Error:threadtest.cpp(30,19):Call to undefined function '_beginthread'
^^ That bits got a red exclamation mark ^^

Warn has a yellow excalamation mark.

Info has no exclamation mark.
0
 
LVL 13

Expert Comment

by:SteH
ID: 11963258
In main.cpp you need the following

   FThread = new TMyThread (true);
   FThread->Priority = tpLower;
   FThread->Resume();

in TMyThread.cpp (class TMyThread : public TThread in header)

TMyThread::Execute ()
{
   while (!Terminated) {
        // here comes your code
   }
}
0
 
LVL 2

Author Comment

by:jonnykeogh
ID: 11963511
OK, totally confused, could you create some sample code that will create a couple of threads and show me some interaction coming from them.

Thnx,
Jonny
0
 
LVL 13

Expert Comment

by:SteH
ID: 11963797
Can you be a bit more specific? IMHO you create a thread when you can seperate its work from the main thread. There should be as little interaction with the main thread or even between threads. Interaction raises the need for proper synchronization which adds even more complexity to an application than threads alone would do. Unproblematic interaction is sending message to and from the thread. There are good articles on messages on flounder:
http://www.flounder.com/mvp_tips.htm#Habits%20Highly%20Defective
and messages can be used in BCB as in VC++.
0
 
LVL 2

Author Comment

by:jonnykeogh
ID: 11964716
Could you make some code that shows text printing away in the background whilst a message box is open? or something

Thnx,
Jonny K
0
 
LVL 13

Accepted Solution

by:
SteH earned 125 total points
ID: 11964872
What about a modelesss dialog displaying text. That way you can do the printing seperatly without any additional threads. (Not counting threads windows creates for additional windows with message queue).

I don't have BCB at hand so it won't be code to paste and compile.

   FThread = new TMyThread (true);
   FThread->Priority = tpLower;
   FThread->SetData (&buffer); // make the buffer with the content to print available for the thread.
   FThread->Resume();
   
   FDlg = new TMyDialog ();
   FDlg->DoModal ();

   FThread->Terminate (); // thread could be terminated already.
   // how to make the main thread aware of the fact that thread has terminated while message box is open
   // I can't think of at the moment.
   // wait for termination;
   delete FThread;

And in
TMyThread::Execute ()
{
   TFile* pOut = new TFile ("LPT1"); // don't know whether file could be a normal variable or need to be pointer
   pOut->Write (buffer); // check syntax. I can't without BCB.
   pOut->close ();
   delete pOut;
}  // terminating.

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
returning a dereferenced pts in C++ 10 141
Fast access to array, using indexes, smart iterative search 2 107
White board coding practice 3 77
Path to  STL Map header file 1 41
Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now