Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Threads (http://www.go4expert.com/forums/threads-t20222/)

shenberry 28Nov2009 20:42

Threads
 
This is a simple calculation from 1 - 100 when not in threads, now all I have to do is create a thread and show the program runs faster.

This is what I have, but the output is garbage and takes longer than the single.

Code:

// multi-threading.cpp : main project file.

#include "stdafx.h"
#include<iostream>
#using <mscorlib.dll>
using namespace std;
using namespace System;
using namespace System::Threading;
using namespace System::Timers;

 // Simple threading scenario:  Start a Shared method running
 // on a second thread.
 public class ThreadExample
 {
 public:
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding
    // the rest of its time slice each time, and then ends.
    static void ThreadProc()
    {
        for(int c = 51; c < 101; c++)
        {
            cout << c << "| ";
            for(int i = 1; i < 101; i++)
            {
                cout << i * c << '\t';
            }
            cout << endl << endl;
            Thread::Sleep(0);
        }
    }
 };
 
 int main()
 {
    int start = Environment::TickCount;
    Console::WriteLine("Main thread: Start a second thread.");
    // Create the thread, passing a ThreadStart delegate that
    // represents the ThreadExample::ThreadProc method.  For a
    // delegate representing a static method, no object is
    // required.
    Thread ^oThread = gcnew Thread(gcnew ThreadStart(&ThreadExample::ThreadProc));
 
    // Start the thread.  On a uniprocessor, the thread does not get
    // any processor time until the main thread yields.  Uncomment
    // the Thread.Sleep that follows t.Start() to see the difference.
    oThread->Start();
    //Thread::Sleep(0);

    for(int c = 1; c < 101; c++)
    {         
        cout << c << "| ";
        for(int i = 1; i < 101; i++)
        {
            cout << i * c << '\t';
        }
        cout << endl << endl;
        Thread::Sleep(0);
    }
   
    Console::WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
    oThread->Join();

    //Console::WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
    //Console::ReadLine();
    return 0;
 }



All times are GMT +5.5. The time now is 18:01.