0

我想很好地了解 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;
}
4

0 回答 0