C++ 多线程多进程问题
发布网友
发布时间:2022-04-26 18:41
我来回答
共2个回答
热心网友
时间:2023-11-12 14:58
#include <iostream>
#include <windows.h>
#include <cmath>
#include <process.h>
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
热心网友
时间:2023-11-12 14:58
代码
注释