Solved

Threads

Posted on 2004-09-02
18
377 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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

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…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

757 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

19 Experts available now in Live!

Get 1:1 Help Now