fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5.  
  6. // ฟังก์ชันสำหรับสร้าง thread
  7. void *threadFunc(void *arg) {
  8. int thread_id = *((int *)arg); // รับค่า id ของ thread
  9.  
  10. // แสดงผลลัพธ์การทำงานของแต่ละ thread
  11. printf("Thread %d is running...\n", thread_id);
  12.  
  13. // รอสักพักเพื่อทำให้ thread ทำงานอยู่เป็นเวลาหนึ่ง
  14. sleep(5);
  15.  
  16. printf("Thread %d is done.\n", thread_id);
  17.  
  18. return NULL; // สิ้นสุดการทำงานของ thread
  19. }
  20.  
  21. int main() {
  22. int choice;
  23. int thread_id = 0;
  24. pthread_t tid;
  25.  
  26. while (1) {
  27. // แสดงเมนูให้ผู้ใช้เลือก
  28. printf("\nMenu:\n");
  29. printf("1. Run thread 1\n");
  30. printf("2. Run thread 2\n");
  31. printf("3. Run thread 3\n");
  32. printf("4. Exit\n");
  33. printf("Enter your choice: ");
  34. scanf("%d", &choice);
  35.  
  36. if (choice == 4) {
  37. printf("Exiting program...\n");
  38. break;
  39. }
  40.  
  41. // สร้าง thread ใหม่เมื่อผู้ใช้เลือกเมนูที่ 1, 2, หรือ 3
  42. if (choice >= 1 && choice <= 3) {
  43. thread_id++;
  44. printf("Creating thread %d...\n", thread_id);
  45. pthread_create(&tid, NULL, threadFunc, &thread_id);
  46. pthread_join(tid, NULL); // รอให้ thread ทำงานเสร็จสิ้นก่อนที่จะดำเนินการต่อ
  47. } else {
  48. printf("Invalid choice. Please enter again.\n");
  49. }
  50. }
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 5280KB
stdin
4
stdout
Menu:
1. Run thread 1
2. Run thread 2
3. Run thread 3
4. Exit
Enter your choice: Exiting program...