Thread: Multithreaded

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    155

    Multithreaded

    Hi, I am learning Multithreadeding and I think I got what this site down ok, but when I went to run it, it still didnt do what I want it to do. See my program needs to run 2 loops, 1st loop is the time, it looks at the time on the sysem and shows you the time every 1 sec. 2end loop is the main program, it had to wait for input from the user so thats why they cant be togather in one thread. Maybe you can tell me what I can do differntly or some other way of doing it maybe? This is whats the base of the Multithreadeding half.
    Code:
    #include <windows.h>
    #include <process.h>
    #include <iostream>
    using namespace std;
    
    void Func1(void *);
    void Func2(void *);
    
    CRITICAL_SECTION Section;
    
    int main()
    {
        HANDLE hThreads[2];
        InitializeCriticalSection(&Section);
    hThreads[0] = (HANDLE)_beginthread(Func1,0,NULL);
    hThreads[1] = (HANDLE)_beginthread(Func2,0,NULL);
    WaitForMultipleObjects(2,hThreads,TRUE,INFINITE);
        DeleteCriticalSection(&Section);
        cout << "Main exit" << endl;
        return 0;
    }
    
    void Func1(void *P){
        int Count;
    
        for (Count = 1; Count < 11; Count++){
            EnterCriticalSection(&Section);
            cout << "Func1 loop " << Count << endl;
            LeaveCriticalSection(&Section);}
        return;
    }
    
    void Func2(void *P){
        int Count;
    
        for (Count = 10; Count > 0; Count--){
            EnterCriticalSection(&Section);
            cout << "Func2 loop " << Count << endl;
            LeaveCriticalSection(&Section);}
        return;
    }

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    What exactly is the program doing wrong, or what do you want it to do? Using a critical section doesn't guarantee the order your threads will be processed. In your example, It's still possible for the first thread to output it's entire loop before the second thread outputs anything (though that'd be very unlikely to happen).
    Last edited by Syneris; 02-02-2006 at 09:06 PM.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    I am learning Multithreadeding and I think I got what this site down ok
    Is there a multithreading tutorial on this site?

  4. #4
    Registered User
    Join Date
    Dec 2005
    Posts
    155
    Quote Originally Posted by Syneris
    What exactly is the program doing wrong, or what do you want it to do? Using a critical section doesn't guarantee the order your threads will be processed. In your example, It's still possible for the first thread to output it's entire loop before the second thread outputs anything (though that'd be very unlikely to happen).
    Like I said, I want it to run my 2 loops, at the same time, but see it doesnt.

    Is there a multithreading tutorial on this site?
    No, theres not... thats why I said there is, unless you were asking if there was on cprogramming, I dont think there is then.
    Last edited by adr; 02-03-2006 at 04:12 AM.

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    No, theres not... thats why I said there is, unless you were asking if there was on cprogramming, I dont think there is then.
    Thanks for clearing that up.

  6. #6
    chococoder
    Join Date
    Nov 2004
    Posts
    515
    Like I said, I want it to run my 2 loops, at the same time, but see it doesnt.
    unless you are running on a multi-CPU system that's never going to happen. You'll get thread scheduling but you'll get only one thread running at any time.

  7. #7
    Registered User
    Join Date
    Dec 2005
    Posts
    155
    Then how does window do it? That clock on the botten of your screen and the start botten on the other side? The start botten on the other side it waiting for input as the clock tells the time, updateing it self ever few 1sec.?

  8. #8
    chococoder
    Join Date
    Nov 2004
    Posts
    515
    each process gets a few milliseconds in rapid succession. That way it SEEMS like they're all working at the same time when in fact they're timesharing.

    You might see your threads skip back and forth but they're done so quickly there's a very good chance they'll complete before their first timeslice is up.

  9. #9
    I am me, who else?
    Join Date
    Oct 2002
    Posts
    250
    Basically unless you need true parallelism, multi-threading is good at doing more than one task quickly (making it seem almost parallel). As it stands now, if you have a dual-core processor, you could probably achieve almost true parallelism.

    As far as I am aware, threading is the best approach to this sort of problem. Or perhaps implementing a message queue which mimcs this. For simplicity's sake keep on with threading. That would be my advice.

  10. #10
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    1. You should use _beginthreadex. _beginthread may automatically close the thread handle before you wait on it. _beginthreadex requires you to explicitly close the returned handle with CloseHandle.

    2. Add a call to Sleep in your thread functions. This will slow them down and allow you to see the effect of multi-threading.
    Code:
    void Func1(void *P){
        int Count;
    
        for (Count = 1; Count < 11; Count++){
            EnterCriticalSection(&Section);
            cout << "Func1 loop " << Count << endl;
            LeaveCriticalSection(&Section);
            Sleep(10);
        }
        return;
    }

  11. #11
    Registered User
    Join Date
    Dec 2005
    Posts
    155
    Ok, I tryed it again, but still nothing. I dont think I can do thisXD
    I want it to display the time and then my code all on the same screen but like refesh the time code only. I cant tho for that the my other code, the main code, needs input from the user, also there is a cleaner code to clean my screen after the use of the codes. Use multithreading I get the same thing again like I did using 1 thread, but if I want to I need another cpu? Why cant a cpu do 2 while loops at ones? Thats what my main code it runing on in the loops, it waits for pQuit to trun true.

  12. #12
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    Post some code that's more relevant to what you're actually doing. It's hard for us to see what's wrong without something more specific in this case.

  13. #13
    Registered User
    Join Date
    Dec 2005
    Posts
    155
    Code:
    #include "tt.h"
    #include <process.h>
    using namespace std;
    void clrscr();
    
    void Func1(void *);
    void Func2(void *);
    
    CRITICAL_SECTION Section;
    
    int main()
    {
    HANDLE hThreads[2];
    InitializeCriticalSection(&Section);
    hThreads[0] = (HANDLE)_beginthread(Func1,0,NULL);
    hThreads[1] = (HANDLE)_beginthread(Func2,0,NULL);
    WaitForMultipleObjects(2,hThreads,TRUE,INFINITE);
    DeleteCriticalSection(&Section);
    cout << "Main exit" << endl;
    }
    void clrscr()
    {
        COORD coordScreen = { 0, 0 };
        DWORD cCharsWritten;
        CONSOLE_SCREEN_BUFFER_INFO csbi;
        DWORD dwConSize;
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        GetConsoleScreenBufferInfo(hConsole, &csbi);
        dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
        FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
        GetConsoleScreenBufferInfo(hConsole, &csbi);
        FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
        SetConsoleCursorPosition(hConsole, coordScreen);
    }
    
    void Func1(void *P)
    {
    void clrscr();
    EnterCriticalSection(&Section);
         time_t rawtime;
         struct tm * timeinfo;
         time ( &rawtime );
         timeinfo = localtime ( &rawtime );
         printf ("Current date and time is: %s", asctime (timeinfo));
         Sleep(1000);
         clrscr();
         LeaveCriticalSection(&Section);
    }
    void Func2(void *P)
    {
    //---ints and vars----------------
      double num3;                //--
      double equal1;              //--
      double equal2;              //--
      int input;                  //--
      long c;                     //--
      float equal;                //--
      float a;                    //--
      float b;                    //--
      float d;                    //--
      float e;                    //--
      float f;                    //--
      float per1;                 //--
      float per2;                 //--
      string name;                //--
      string info;                //--
      string my_string2 = ".txt"; //--
      string my_string3;          //--
      string pick;                //--
      string no;                  //--
      string yes;                 //--
    //--------------------------------
    EnterCriticalSection(&Section);
    bool pQuit = false;
     while( false == pQuit )
     {
    //--------menu---------------------------
      cout<<"0. Exit\n";                 //--
      cout<<"1. Add\n";                  //--
      cout<<"2. Subtract\n";             //--
      cout<<"3. Multiply\n";             //--
      cout<<"4. Divide\n";               //--
      cout<<"5. Absolute Value\n";       //--
      cout<<"6. Percent of\n";           //--
      cout<<"7. Linear Euations Slops\n";//--
      cout<<"8. Polygons\n";             //--
      cout<<"9. Open File\n";            //--
      cout<<"10. Save File\n";           //--
      cout<<"11. Size of File\n";        //--
      cout<<"Selection: ";               //--
    //---------------------------------------
    
    //----------code---------->
      cin>> input;
      switch ( input ) {
      case 0: //Exit
        pQuit = true;
        break;
      case 1: //Add
        cout << "Enter two numbers to add: "<<endl;
        cout << ">";
        cin  >> a;
        cout << ">";
        cin  >> b;
        equal = a+b;
        cout << "answer = "<<equal<<endl;
        system("pause");
        clrscr();
        break;
      case 2: //Subtract
        cout << "Enter two numbers to subtract: "<<endl;
        cout << ">";
        cin  >> a;
        cout << ">";
        cin  >> b;
        equal = a-b;
        cout << "answer = " <<equal<<endl;
        system("pause");
        clrscr();
        break;
      case 3:  //Multiply
        cout << "Enter two numbers to multiply: "<<endl;
        cout << ">";
        cin  >> a;
        cout << ">";
        cin  >> b;
        equal = a*b;
        cout << "answer = " <<equal<<endl;
        system("pause");
        clrscr();
        break;
      case 4:  //Divide
        cout << "Enter two numbers to divide: "<<endl;
        cout << ">";
        cin  >> a;
        cout << ">";
        cin  >> b;
        equal = a/b;
        cout << "answer = " <<equal<<endl;
        system("pause");
        clrscr();
        break;
      case 5:  //Absolute value
        cout << "Enter a number to find its absolute value: "<<endl;
        cout << ">";
        cin  >> c;
        equal = abs(c);
        cout << "answer = " <<equal<<endl;
        system("pause");
        clrscr();
        break;
      case 6:  //Percent of
        cout << "Enter two numbers (ex. 25 of 75 = 33.33%) "<<endl;
        cout << ">";
        cin >> per1;
        cout << ">";
        cin >> per2;
        equal2 = (per1 / per2) * 100;
        cout << "answer = " << equal2 << "%"<<endl;
        system("pause");
        clrscr();
        break;
      case 7: //Linear Equations Slops
        cout << "What is the y m x (ex. (2,5) m=1 so y=1 m=5 x=2) "<<endl;
        cout << ">";
        cin >> a;
        cout << ">";
        cin >> b;
        cout << ">";
        cin >> d;
        equal=b*d;
        f=equal-a;
        cout << "answer is y="<<a<<"x="<<f<<endl;
        system("pause");
        clrscr();
        break;
      case 8:  //Polygon
        cout << "Enter a polygon number: "<<endl;
        cout << ">";
        cin  >> a; 
        if(a == 1)
            cout<< "Does not exist"<<endl;
        else if(a == 2)
            cout<< "Does not exist"<<endl;
        else if(a == 3)
            cout<< "Tigon"<<endl;
        else if(a == 4)
            cout<< "Tetragon"<<endl;
        else if(a == 5)
            cout<< "Pentagon"<<endl;
        else if(a == 6)
            cout<< "Hexagon"<<endl;
        else if(a == 7)
            cout<< "Heptagon" <<endl;
        else if(a == 8)
            cout<< "Octagon"<<endl;
        else if(a == 9)
            cout<< "Enneagon"<<endl;
        else if(a == 10)
            cout<< "Decagon"<<endl;
        else if(a == 11)
            cout<< "Hendecagon"<<endl;
        else if(a == 12)
            cout<< "Dodecagon"<<endl;
        else if(a == 13)
            cout<< "Triskaidecagon"<<endl;
        else
            cout << "I'm sorry thats not in my database."<<endl;
        system("pause");
        clrscr();
        break;
      case 9:
       {
        string line;
        cout<<"What is the name of the file? ";
        getchar();
        getline(cin, name);
        my_string3 = name;
        ifstream myfile (my_string3.c_str());
        if (myfile.is_open())
          {
         while (! myfile.eof() )
           {
           getline (myfile,line);
           cout << line << endl;
           }
           myfile.close();
          }
        else cout << "Unable to open file";
        getchar();
        clrscr();
        break;
       }
      case 10:
       {
        cout<<"What is the name of the file? ";
        getchar();
        getline(cin, name);
        ofstream myfile;
        my_string3 = name+my_string2;
        myfile.open (my_string3.c_str());
        cout<<"Please enter what to save: ";
        getline(cin,info);
        myfile << info;
        myfile.close();
        clrscr();
        break;
       }
      case 11: 
       {
         long begin,end;
         cout<<"What is the name of the file? ";
         getchar();
         getline(cin, name);
         my_string3 = name;
         ifstream myfile (my_string3.c_str());
         begin = myfile.tellg();
         myfile.seekg (0, ios::end);
         end = myfile.tellg();
         myfile.close();
         cout << "size is: " << (end-begin) << " bytes."<<endl;
         getchar();
         clrscr();
         break;
       }
      default:
        cout<<"Error, bad input, quitting\n";
        clrscr();
        break;
     }
      cin.get();
     }
    LeaveCriticalSection(&Section);
    }
    Its perty long>< But I want it to post the time and refrush the time everyone 1 sec as the loop waits for input from user. I can make the time refrush it self by puting a another loop but then that will efftect the other one b/c it wont go to the main loop.
    Last edited by adr; 02-04-2006 at 09:49 AM.

  14. #14
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    Your entire while loop in func2 is inside a critical section. This is kind of like telling the program you don't want any other thread to be able to do anything until the while loop finishes. Your func1 only runs once right now. It should be in a loop that also runs until pQuit == false. Whenever you clear the screen, you'll need to redisplay the time. Also, you when the time updates every second you need to update the time display without clearing the screen. I need to go, but if nobody else gives a better solution and you still need help, i'll try to provide a more specific solution.

  15. #15
    Registered User
    Join Date
    Dec 2005
    Posts
    155
    This is kind of like telling the program you don't want any other thread to be able to do anything until the while loop finishes.
    So how would you get it to stop for a sec and get it to do the 1func?
    Your func1 only runs once right now.
    I know, I took it out for a bit so I can run it.
    Also, you when the time updates every second you need to update the time display without clearing the screen.
    Ok I can do that also.
    Code:
    #include <cstdlib>
    #include <ctime>
    #include <iostream>
    #include <windows.h>
    using namespace std;
    
    DWORD WINAPI ThreadProc(LPVOID param)
    {
        time_t t;
        struct tm* tm;
        char buf[126];
        for(;;)
        {
            t = time(0);
            tm = localtime(&t);
            sprintf(buf,"%02d/%02d/%04d %02d:%02d:%02d",
                  tm->tm_mon+1,tm->tm_mday,tm->tm_year+1900,
                  tm->tm_hour,tm->tm_min,tm->tm_sec);
            cout << "\r" << buf;
            Sleep(1000);   
        }
        return 0;
    }
    int main(int argc, char *argv[])
    {
        HANDLE hThred;
        DWORD dwThreadID;
        hThred = CreateThread(0,0,ThreadProc,0,0,&dwThreadID);
        system("PAUSE");
        return EXIT_SUCCESS;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MultiThreaded GUI.
    By execute in forum Windows Programming
    Replies: 6
    Last Post: 05-18-2006, 01:00 PM
  2. Multithreaded server, where to start?
    By Ichmael™ in forum Windows Programming
    Replies: 1
    Last Post: 02-26-2006, 01:17 AM
  3. Multithreaded computer language
    By Sang-drax in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 09-17-2004, 08:51 PM
  4. Multithreaded Winsock
    By X PaYnE X in forum Windows Programming
    Replies: 6
    Last Post: 01-05-2004, 09:00 AM
  5. Multithreaded Webchat-Server
    By Spark in forum C Programming
    Replies: 3
    Last Post: 05-23-2002, 04:16 PM