• 多线程程序的奇怪问题记录


    代码如下:

     1 #include <unistd.h>                                                                                                                                                                         
     2 #include <stdlib.h>
     3 #include <string.h>
     4 #include <pthread.h>
     5 #include <stdio.h>
     6 char message[] = "Hello world!";
     7 int runNow = 1;
     8 static int printCount = 0;
     9 
    10 void *threadFunction(void *arg){
    11     //int printCount = 0;
    12 
    13     while(printCount-- > 0){
    14         if(runNow == 2){
    15             printf("2");
    16             runNow = 1;
    17         }else{
    18             sleep(1);
    19         }
    20     }
    21     sleep(3);
    22 }
    23 
    24 int main(int argc, char **argv)
    25 {
    26     pthread_t threadA;
    27     int printCount1 = 0;
    28     void *threadResult;
    29     int res = pthread_create(&threadA, NULL, threadFunction, (void *)message);
    30 
    31     if(res != 0){
    32         perror("Thread creation failed!");
    33         exit(EXIT_FAILURE);
    34     }
    35 
    36     while(printCount++ < 20){
    37         if(runNow == 1){
    38             printf("1");
    39             runNow = 2;
    40         }else{
    41             sleep(1);
    42         }
    43     }
    44 
    45     printf("Waiting for thread to finish...
    ");
    46     res = pthread_join(threadA, &threadResult);
    47     if(res != 0){
    48         perror("Thread join failed");
    49         exit(EXIT_FAILURE);
    50     }
    51     printf("Thread joined
    ");
    52 
    53     exit(EXIT_SUCCESS);
    54 }

    编译:gcc -g thread2.c -o thread2 -lpthread

    运行结果可以是以下几种:

    1  thread2
    12121212121212121212121Waiting for thread to finish...
    Thread joined
    
     2 thread2
    121Waiting for thread to finish...
    Thread joined
    
     3 thread2
    121Waiting for thread to finish...
    Thread joined
    
     4 thread2
    12121Waiting for thread to finish...
    Thread joined
    
     5 thread2
    121212121Waiting for thread to finish...
    Thread joined

    还在思索中

    #include <pthread.h>
  • 相关阅读:
    一道C#基础题,看你能多长时间做出来?
    终于能在这里安家了
    你知道返回多少吗?(使用Math类)
    关于implicit和explicit关键词的用法
    关于基类与派生类的学习
    js控制输入框
    Oracle 动态SQL返回单条结果和结果集 转帖
    定时器:.NET Framework类库中的Timer类比较(转帖)
    UVA10020 Minimal coverage
    UVA1388 Graveyard
  • 原文地址:https://www.cnblogs.com/guochaoxxl/p/14254155.html
Copyright © 2020-2023  润新知