multi_pthread.c 772 B

12345678910111213141516171819202122232425262728293031323334
  1. #include <pthread.h>
  2. #include <stdatomic.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #define THREAD_NUM 32
  7. #define CONC_THREAD_NUM 4
  8. atomic_int counter = 0;
  9. void* inc(void* arg) {
  10. counter++;
  11. return NULL;
  12. }
  13. int main(int argc, char** argv) {
  14. for (int i = 0; i < THREAD_NUM; i++) {
  15. pthread_t thread[CONC_THREAD_NUM];
  16. /* create several threads running in parallel */
  17. for (int j = 0; j < CONC_THREAD_NUM; j++) {
  18. pthread_create(&thread[j], NULL, inc, NULL);
  19. }
  20. /* join threads and continue with the next batch */
  21. for (int j = 0; j < CONC_THREAD_NUM; j++) {
  22. pthread_join(thread[j], NULL);
  23. }
  24. }
  25. printf("%d Threads Created\n", counter);
  26. return 0;
  27. }