thread.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. #if 0
  35. if(r==0) {
  36. r = pthread_setschedprio(h->tid, prio);
  37. if(r) {
  38. printf("____ set thread prio %d failed\n", prio);
  39. }
  40. }
  41. #endif
  42. pthread_attr_destroy(&attr);
  43. return r;
  44. }
  45. int thread_stop(int id)
  46. {
  47. if(id>=THREAD_ID_MAX) {
  48. return -1;
  49. }
  50. thread_handle_t *h=&myThdHandles[id];
  51. h->quit = 1;
  52. pthread_join(h->tid, NULL);
  53. h->tid = 0;
  54. h->arg = NULL;
  55. h->fn = NULL;
  56. return 0;
  57. }
  58. int thread_stop_all(void)
  59. {
  60. int i;
  61. for(i=0; i<THREAD_ID_MAX; i++) {
  62. thread_stop(i);
  63. }
  64. return 0;
  65. }
  66. int thread_start_simp(thread_fn fn, void *arg, int stksize)
  67. {
  68. int r;
  69. pthread_t tid;
  70. pthread_attr_t attr;
  71. pthread_attr_init(&attr);
  72. pthread_attr_setstacksize(&attr, stksize);
  73. r = pthread_create(&tid, &attr, fn, arg);
  74. pthread_attr_destroy(&attr);
  75. return r;
  76. }
  77. int thread_print_stacksize(void)
  78. {
  79. int r;
  80. size_t size;
  81. pthread_attr_t attr;
  82. r = pthread_attr_init(&attr);
  83. if(r) {
  84. printf("___ print stacksize, attr init failed\n");
  85. return -1;
  86. }
  87. r = pthread_attr_getstacksize(&attr, &size);
  88. if(r) {
  89. printf("___ print stacksize, attr init failed\n");
  90. }
  91. else {
  92. printf("_____ stacksize: %dMB\n", size/MB);
  93. }
  94. pthread_attr_destroy(&attr);
  95. return r;
  96. }