zoukankan      html  css  js  c++  java
  • 多线程程序的奇怪问题记录

    代码如下:

     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>
  • 相关阅读:
    Luogu P3275 糖果
    Python基础学习
    SharePoint 2013
    Office
    KnockoutJS
    SharePoint 2013
    Bootstrap
    SharePoint 2013
    CSS
    AngularJS
  • 原文地址:https://www.cnblogs.com/guochaoxxl/p/14254155.html
Copyright © 2011-2022 走看看