Advertisement
Guest User

Untitled

a guest
Feb 21st, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <conio.h>
  4. #include <Windows.h>
  5.  
  6. using namespace std;
  7.  
  8. #define MAX_THREADS 100
  9.  
  10. CRITICAL_SECTION cs;
  11.  
  12.  
  13. void task(void)
  14. {
  15.   while (true)
  16.   {
  17.     char *buffer;
  18.     EnterCriticalSection(&cs);
  19.     buffer = (char *)malloc(4096);
  20.     LeaveCriticalSection(&cs);
  21.  
  22.     if (buffer == NULL)
  23.     {
  24.       cout << "malloc error" << endl;
  25.     }
  26.  
  27.     EnterCriticalSection(&cs);
  28.     free(buffer);
  29.     LeaveCriticalSection(&cs);
  30.   }
  31. }
  32.  
  33. int main(int argc, char** argv)
  34. {
  35.   if (!InitializeCriticalSectionAndSpinCount(&cs, 0x00000400))
  36.   {
  37.     printf("Error\n");
  38.     _getch();
  39.   }
  40.  
  41.   thread some_threads[MAX_THREADS];
  42.  
  43.   for (int i = 0; i < MAX_THREADS; i++)
  44.   {
  45.     some_threads[i] = thread(task);
  46.   }
  47.  
  48.   for (int i = 0; i < MAX_THREADS; i++)
  49.   {
  50.     some_threads[i].join();
  51.   }
  52.  
  53.   _getch();
  54.   return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement