Solved

Threads

Posted on 2004-09-02
18
380 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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
 
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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 viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

829 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