测试线程并发

时间:2013-05-29 14:58:27

标签: c++ multithreading concurrency

我想了解Code Profiler软件正在发生的事情。为此,我想创建一个我会心里明白的程序并在其上使用分析器。

我认为这有助于了解分析的工作原理。

所以我试着制作一个程序来说明线程的并发性......但我认为我没有什么好的东西。你能帮助我把它变成真正的并发问题吗?

我在互联网上找不到任何好的例子!

#include <iostream>
#include <process.h>
#include <unistd.h>
#include <windows.h>
using namespace std;

int i = 0;
int j = 0;
int k = 0;
bool thread1Finished = false;
bool thread2Finished = false;

void thread1(void *param) {
    cout << "In Thread 1 Function" << endl;
    j = i;
    Sleep(1000); // Sleep for 1 second
    cout << "Thread 1 j is : " << j << endl;
    j++;
    cout << "Thread 1 j is : " << j << endl;
    cout << "Thread 1 Function Ends" << endl;
    thread1Finished = true;
    _endthread();
}

void thread2(void *param) {
    cout << "In Thread 2 Function" << endl;
    j = i;
    Sleep(200); // Sleep for 1 second
    cout << "Thread 2 j is : " << j << endl;
    j++;
    cout << "Thread 2 j is : " << j << endl;
    cout << "Thread 2 Function Ends" << endl;
    thread2Finished = true;
    _endthread();
}

int main() {
    cout << "Starting Thread 1" << endl;
    cout << _beginthread(thread1, 0, NULL);

    //while(!thread1Finished) {
    //    Sleep(10);
    //}

    cout << "\n" << endl;

    cout << "Starting Thread 2" << endl;
    cout << _beginthread(thread2, 0, NULL);

    while(!thread1Finished || !thread2Finished) {
        Sleep(10);
    }

    cout << "Main ends" << endl;
    return 0;
}

0 个答案:

没有答案