一般情况下,线程在主函数创建,函数分配在栈区,遵循先进后出规则,先创建后运行

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
 
int var  = 8;
 
void *thread_1(void *arg)
{
    while(1)
    {
        printf("this is my new thread1: var++\n");
        var++;
        sleep(1);
    }
    return NULL;
}
 
void *thread_2(void * arg)
{
    while(1){
        printf("this is my new thread2: var = %d\n", var);
        sleep(1);
    }
    
    return NULL;
}
 
int main(int argc, char *argv[])
{
    pthread_t tid1,tid2;
    
    //创建两个线程
    pthread_create(&tid1, NULL, thread_1, NULL);  
    pthread_create(&tid2, NULL, thread_2, NULL);
    
    while(1){
        printf("the main thread: var = %d\n", var);
        sleep(1);
    }
    
    return 0;
}

 

线程执行顺序之一

相关文章:

  • 2022-01-08
  • 2022-12-23
  • 2022-02-08
  • 2021-05-20
  • 2022-12-23
  • 2021-12-12
  • 2021-08-12
  • 2021-04-26
猜你喜欢
  • 2022-12-23
  • 2022-01-29
  • 2021-09-04
  • 2022-12-23
  • 2021-08-19
  • 2021-12-20
  • 2022-12-23
相关资源
相似解决方案