【IO】线程函数(creat)线程翻转数组

1.标准IO函数时候讲解的时钟代码,要求输入quit字符串后,结束进程

#include<stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
void *callBack(void* arg)
{
	time_t t;
	while(1)
	{
		//printf("exit q");
		t = time(NULL);
		struct tm* insert = localtime(&t);
		printf("%d-%2d-%2d-%2d:%2d:%2d\r",\
				insert->tm_year+1900,insert->tm_mon+1,insert->tm_mday,\
				insert->tm_hour,insert->tm_min,insert->tm_sec);
		fflush(stdout);
		sleep(1);
	}

}
int main(int argc, const char *argv[])
{
	char q[10] = "";
	pthread_t tid;
	if(pthread_create(&tid,NULL,callBack,NULL)!=0)
	{
		printf("pthread_create failed\n");
		return -1;
	}
	while(1)
	{
		scanf("%s",q);
		if(!strcmp(q,"quit"))
			exit(0);
	}
	return 0;
}

2,
在这里插入图片描述

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

char buf[] = "1234567";
int flag = 1;//1打印 0逆转
void *callBack1(void* arg)
{
	while(1)
	{
		if(1 == flag)
		{
			printf("%s\n",buf);
			flag = 0;
		}
	}
	pthread_exit(NULL);
}
void *callBack2(void* arg)
{
	int i = 0, j = 6;
	int k = 3;
	while(1)
	{
		if(0 == flag)
		{
			while(i < j)
			{
				char c;
				c = buf[i];
				buf[i] = buf[j];
				buf[j] = c;
				i++;
				j--;

			}	
		}
		flag = 1;
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	pthread_t tid1,tid2;
	pthread_create(&tid1,NULL,callBack1,NULL);
	pthread_create(&tid2,NULL,callBack2,NULL);
	while(1);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用`pthread_create`函数创建线程,你需要包含`pthread.h`头文件,并按照以下方式调用该函数: ```c #include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { // 线程执行的代码 printf("Hello from new thread!\n"); return NULL; } int main() { pthread_t thread; int ret; // 创建线程 ret = pthread_create(&thread, NULL, thread_func, NULL); if (ret != 0) { printf("Failed to create thread: %d\n", ret); return 1; } // 等待线程结束 ret = pthread_join(thread, NULL); if (ret != 0) { printf("Failed to join thread: %d\n", ret); return 1; } printf("Thread finished.\n"); return 0; } ``` 在上面的代码中,定义了一个新线程的入口函数`thread_func`。然后,在`main`函数中,使用`pthread_create`函数创建一个新线程,并将线程函数`thread_func`作为参数传递给它。`pthread_create`函数的第一个参数是一个指向线程标识符的指针,用于存储新线程的ID。第二个参数是线程属性,这里我们传递了NULL表示使用默认属性。第三个参数是线程函数的指针,最后一个参数是传递给线程函数的参数。 创建线程成功后,我们使用`pthread_join`函数等待新线程的结束。`pthread_join`函数的第一个参数是要等待的线程ID,第二个参数是指向线程返回值的指针,我们在这里传递了NULL,因为在`thread_func`中没有返回值。 最后,我们输出一条消息表示主线程的执行已经结束。 希望这个例子能帮助到你!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值