linux c | 子线程和主线程交替循环

润和面试题

子线程循环 3 次,接着主线程循环 6 次,接着又回到子线程循环 3 次,接着再回到主线程又循环6 次,如此循环50次,试写出代码。

主要考察线程的创建、等待以及终止。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>

int thread1()
{
    int ret = 0;
    ret = pthread_self();
    printf("This is child pthread %d\n", ret);
    //sleep(1);
    pthread_exit("1");
}

int main(){
    pthread_t tid;
    void * pthread_return;
    int ret = 0;
    int i = 0;
    int num = 0;

    while(num <= 50)
    {
        for(i = 0; i < 3; i++)
        {
            printf("%d:", num);                          //account
            if(++num > 50)
            {
                break;
            }
            
            ret = pthread_create(&tid, NULL, (void *)thread1, NULL);        //create pthread 1
            if(ret != 0)
            {
                printf("Fail!\n");
            }
            //printf("Wait1...\n");
            ret = pthread_join(tid, &pthread_return); 
             
        }
                            //wait the pthread 1 exit
        if(ret != 0)
        {
            printf("Fail too...\n");
        }

        for(i = 0; i < 6; i++)                                               //main pthread
        {
            if(++num > 50)
            {
                break;
            }
            ret = pthread_self();
            printf("%d:This is main pthread %d\n", num, ret);
            //sleep(1);
        }
    }
    return 0;
}

代码中,可以使用sleep函数,达成一秒打印一句的效果,更便于观察。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值