C++ 多线程多进程问题

2025-03-11 05:18:43
推荐回答(2个)
回答1:

#include 
#include 
#include 
#include 

using namespace std;

CRITICAL_SECTION cs;         // critical section for multiple threads sync.
volatile long counter = 0;  // counter for looping thru the number range.

bool isPrime(const long n); // prime number check function.
unsigned int __stdcall thread_primeCheck(void*); // prime number check thread.

int main(int argc, char const *argv[])
{
    HANDLE h_thread_1, h_thread_2;
    
    InitializeCriticalSection(&cs); // initial cs.
    // create threads
    h_thread_1 = (HANDLE)_beginthreadex(0, 0, &thread_primeCheck, (void*)0, 0, 0);
    h_thread_2 = (HANDLE)_beginthreadex(0, 0, &thread_primeCheck, (void*)0, 0, 0);
    
    // set the thread-sync signal.
    WaitForSingleObject(h_thread_1, INFINITE);
    WaitForSingleObject(h_thread_2, INFINITE);

    // wrapped-up, close handle & delete the cs.
    CloseHandle(h_thread_1);
    CloseHandle(h_thread_2);

    DeleteCriticalSection(&cs);

    return 0;
}

// function to check if a given number: n is a prime number
bool isPrime(const long n)
{
    for (long l = 2; l < (long)(sqrt((double)n) + 1.0); ++l)
        if (n % l == 0) return false;

    return true;
}

// thread function definition.
unsigned int __stdcall thread_primeCheck(void*)
{
    while (counter < 10000) {
        EnterCriticalSection(&cs); // enter cs here!, protection area.
        long num = counter ++;        
        if ( isPrime(num) ){
            prime_number ++;
            cout << " " << num << endl;
        }
        LeaveCriticalSection(&cs); // leave cs.
    }
}

运行:

2
3
5
...
9949
9967
9973
Total prime numbers : 1231

回答2:

代码
注释