You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

39 lines
837 B

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <pthread.h>
  8. typedef struct {
  9. pthread_t id;
  10. int i;
  11. char mes[256];
  12. } Thread;
  13. void *print_thread(void *argv) {
  14. Thread *t = argv;
  15. printf("%d %lu %s\n", t->i, t->id, t->mes);
  16. pthread_exit(NULL);
  17. return NULL;
  18. }
  19. int main(int argc, char **argv){
  20. if (argc != 2) {
  21. printf("Usage: %s [n]\n", argv[0]);
  22. exit(1);
  23. }
  24. int n = atoi(argv[1]);
  25. Thread threads[n];
  26. for (int i = 0; i < n; ++i) {
  27. threads[i].i = i;
  28. snprintf(threads[i].mes, 256, "Hello from thread %d", i);
  29. printf("Thread %d is created\n", i);
  30. pthread_create(&threads[i].id, NULL, &print_thread, &threads[i]);
  31. pthread_join(threads[i].id, NULL);
  32. }
  33. }