thread.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include "thread.h"
  2. static thread_handle_t myThdHandles[THREAD_ID_MAX]={0};
  3. int thread_start(int id, thread_fn fn, void *arg, int stksize, int prio)
  4. {
  5. int r;
  6. pthread_attr_t attr;
  7. if(id>=THREAD_ID_MAX) {
  8. return -1;
  9. }
  10. thread_handle_t *h=&myThdHandles[id];
  11. h->arg = arg;
  12. h->quit = 0;
  13. r = pthread_attr_init(&attr);
  14. if(r) {
  15. printf("____ thread %d attr init failed\n", id);
  16. return -1;
  17. }
  18. #if 0
  19. h->stk = malloc(stksize);
  20. if(h->stk) {
  21. r = pthread_attr_setstack(h->stk, stksize);
  22. if(r) {
  23. printf("____ thread %d attr setstack failed\n", id);
  24. }
  25. }
  26. else {
  27. r = pthread_attr_setstacksize(&attr, stksize);
  28. if(r) {
  29. printf("____ thread %d attr setstacksize %d failed\n", id, stksize);
  30. }
  31. }
  32. #endif
  33. r = pthread_create(&h->tid, &attr, fn, h);
  34. pthread_attr_destroy(&attr);
  35. return r;
  36. }
  37. int thread_stop(int id)
  38. {
  39. if(id>=THREAD_ID_MAX) {
  40. return -1;
  41. }
  42. thread_handle_t *h=&myThdHandles[id];
  43. h->quit = 1;
  44. pthread_join(h->tid, NULL);
  45. h->tid = 0;
  46. h->arg = NULL;
  47. h->fn = NULL;
  48. return 0;
  49. }
  50. int thread_stop_all(void)
  51. {
  52. int i;
  53. for(i=0; i<THREAD_ID_MAX; i++) {
  54. thread_stop(i);
  55. }
  56. return 0;
  57. }
  58. int thread_start_simp(thread_fn fn, void *arg, int stksize)
  59. {
  60. int r;
  61. pthread_t tid;
  62. pthread_attr_t attr;
  63. pthread_attr_init(&attr);
  64. pthread_attr_setstacksize(&attr, stksize);
  65. r = pthread_create(&tid, &attr, fn, arg);
  66. pthread_attr_destroy(&attr);
  67. return r;
  68. }
  69. int thread_print_stacksize(void)
  70. {
  71. int r;
  72. size_t size;
  73. pthread_attr_t attr;
  74. r = pthread_attr_init(&attr);
  75. if(r) {
  76. printf("___ print stacksize, attr init failed\n");
  77. return -1;
  78. }
  79. r = pthread_attr_getstacksize(&attr, &size);
  80. if(r) {
  81. printf("___ print stacksize, attr init failed\n");
  82. }
  83. else {
  84. printf("_____ stacksize: %dMB\n", size/MB);
  85. }
  86. pthread_attr_destroy(&attr);
  87. return r;
  88. }