gpt4 book ai didi

创建将当前时间打印到命令行的 pthread

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:42 25 4
gpt4 key购买 nike

我有一个命令行程序,我希望允许用户使用单独的线程打印当前时间。我目前是这样设置的:

我获取用户输入,然后将其与字符串 time 进行比较。如果它们相等,我将创建一个新线程来设置时间变量。

char currentTime[20];
if (strcmp(input, "time") == 0) {
pthread_t thread;
int rc = pthread_create(&thread, NULL, getTime, NULL);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}

我的 getTime 函数:

void getTime() {
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
sprintf(currentTime,"%s", asctime (timeinfo));
printf("%s", currentTime);
pthread_exit(NULL);
}

我从这里得到了一个 Abort trap 6 错误,但是我没有从 pthread 得到任何错误,所以我不确定问题是什么。线程似乎已正确创建。

最佳答案

getTime() 函数不返回任何内容。

currentTime 缓冲区太短。

试试这个:

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

static void * getTime( void * arg ) {
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf("%s", asctime (timeinfo));
return NULL;
}

int main( int argc, char * argv[] ) {
pthread_t thread;
int rc = pthread_create( &thread, NULL, getTime, NULL );
if (rc) {
printf( "ERROR; return code from pthread_create() is %d\n", rc );
exit( -1 );
}
sleep( 1 );
return 0;
}

编译并执行:

$ gcc -Wall -o timeThread timeThread.c -lpthread
$ ./timeThread
Fri Feb 10 19:55:06 2017
$

时间长度为 25 个字符。

注意等待线程执行的sleep(1)指令。

关于创建将当前时间打印到命令行的 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42166538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com