1. 子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码

    [X] 无法锁住的错误解法

    1. #include "comm.h"
    2. pthread_mutex_t gmux = PTHREAD_MUTEX_INITIALIZER;
    3. #define lock pthread_mutex_lock
    4. #define unlock pthread_mutex_unlock
    5. int cnt = 0;
    6. int sta = 1;
    7. volatile int status = 1;
    8. void *child(void *arg) {
    9. int i = 0;
    10. while(1) {
    11. if (!status) {
    12. printf("child over\n");
    13. break;
    14. }
    15. lock(&gmux);
    16. for (i = 0; i < 10; i++) {
    17. printf("child %d\n", i + 1);
    18. }
    19. unlock(&gmux);
    20. sched_yield();
    21. }
    22. return NULL;
    23. }
    24. int main(int argc, char **argv) {
    25. int i;
    26. pthread_t tid;
    27. pthread_create(&tid, NULL, child, NULL);
    28. while(1) {
    29. sched_yield();
    30. lock(&gmux);
    31. for (i = 0; i < 100; i++) {
    32. printf("parent %d\n", i + 1);
    33. }
    34. if (100 == cnt) {
    35. status = 0;
    36. unlock(&gmux);
    37. break;
    38. }
    39. unlock(&gmux);
    40. cnt++;
    41. }
    42. printf("parent over\n");
    43. return 0;
    44. }

    解法一:

    1. #include "comm.h"
    2. pthread_mutex_t gmux = PTHREAD_MUTEX_INITIALIZER;
    3. #define lock pthread_mutex_lock
    4. #define unlock pthread_mutex_unlock
    5. int cnt = 0;
    6. int sta = 1;
    7. volatile int status = 1;
    8. void *child(void *arg) {
    9. int i = 0;
    10. while(1) {
    11. do {
    12. unlock(&gmux);
    13. sched_yield();
    14. lock(&gmux);
    15. } while (0 == sta);
    16. if (!status) {
    17. printf("child over\n");
    18. break;
    19. }
    20. for (i = 0; i < 10; i++) {
    21. printf("child %d\n", i + 1);
    22. }
    23. sta = 0;
    24. }
    25. return NULL;
    26. }
    27. int main(int argc, char **argv) {
    28. int i;
    29. pthread_t tid;
    30. pthread_create(&tid, NULL, child, NULL);
    31. while(1) {
    32. do {
    33. unlock(&gmux);
    34. sched_yield();
    35. lock(&gmux);
    36. } while(1 == sta);
    37. for (i = 0; i < 100; i++) {
    38. printf("parent %d\n", i + 1);
    39. }
    40. if (100 == cnt) {
    41. status = 0;
    42. unlock(&gmux);
    43. break;
    44. }
    45. sta = 1;
    46. cnt++;
    47. }
    48. printf("parent over\n");
    49. return 0;
    50. }

    解法二:(用条件变量)