2月3日 线程

该代码示例定义了一个全局字符串变量charbuf并创建了两个线程。线程一循环打印buf内容,线程二循环倒置buf字符串。由于缺乏同步机制,程序可能会遇到并发问题,导致线程一打印的结果不确定,可能是原始顺序或倒置顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 定义一个全局变量char buf[]=”1234567”,创建两个线程,不考虑退出条件。

  1. 线程一循环打印buf字符串。

  1. 线程二循环倒置buf字符串,即buf中本来存储1234567,倒置后buf中存储7654321,不打印。

  1. 线程一打印出来的结果只能是1234567或7654321.

#include<stdio.h>

#include<sys/types.h>

#include<unistd.h>

#include<stdlib.h>

#include<sys/wait.h>

#include<pthread.h>

#include<string.h>

char buf[]="1234567";

void* callBack1(void* arg)

{

while(1){

printf("%s\n",buf);

sleep(0.5);

}

}

void* callBack2(void* arg)

{

intnum=strlen(buf);

inti=0;

inttemp=0;

while(1){

for(i=0;i<num/2;i++){

temp=buf[i];

buf[i]=buf[num-1-i];

buf[num-1-i]=temp;

}

sleep(1);

}

}

int main(int argc, const char *argv[])

{ pthread_t tid1,tid2;

if(pthread_create(&tid1,NULL,callBack1,NULL)!=0){

fprintf(stderr,"pthread_createerror");

return-1;

}

if(pthread_create(&tid2,NULL,callBack2,NULL)!=0){

fprintf(stderr,"pthread_createerror");

return-1;

}

pthread_detach(tid1);

pthread_join(tid2,NULL);

return0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值