【问题标题】:Create pthread that prints current time to command line创建将当前时间打印到命令行的 pthread
【发布时间】:2017-06-29 05:22:32
【问题描述】:

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

我得到用户输入,然后将其与字符串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 得到任何错误,所以我不确定问题是什么。似乎线程正在正确创建。

【问题讨论】:

  • 你真的读过input的任何东西吗? void getTime() { 应为 void *getTime(void *arg) { 所要求的 pthread_create(),即使您不需要向线程传递任何参数。
  • pthread 函数的签名为:void * getTime( void * arg ),因此您需要做的第一件事是更正您的 getTime() 函数。

标签: c multithreading time pthreads


【解决方案1】:

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) 指令等待线程执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多