【问题标题】:Why do I get "error: ‘pthread_delay_np’ was not declared in this scope"?为什么我会收到“错误:‘pthread_delay_np’未在此范围内声明”?
【发布时间】:2010-11-29 15:40:28
【问题描述】:

我试图查看是否有可能避免线程在 thread_create 之后立即启动。所以,我遇到了 pthread_delay_np 并尝试了这个例子:

#define _MULTI_THREADED
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#define NTHREADS 5

void *threadfunc(void *parm)
{
  int               rc;
  struct timespec   ts = {0, 0};

  /* 5 and 1/2 seconds */
  ts.tv_sec  = 5;
  ts.tv_nsec = 500000000;

  printf("Thread blocked\n");
  rc = pthread_delay_np(&ts);
  if (rc != 0) {
    printf("pthread_delay_np() - return code %d\n", rc);
    return (void*)&rc;
  }
  printf("Wait timed out!\n");

  return NULL;
}

int main(int argc, char **argv)
{
  int                   rc=0;
  int                   i;
  pthread_t             threadid[NTHREADS];
  void                 *status;
  int                   fail=0;

  printf("Enter Testcase - %s\n", argv[0]);

  printf("Create %d threads\n", NTHREADS);
  for(i=0; i<NTHREADS; ++i) {
    rc = pthread_create(&threadid[i], NULL, threadfunc, NULL);
  }

  printf("Wait for threads and cleanup\n");
  for (i=0; i<NTHREADS; ++i) {
    rc = pthread_join(threadid[i], &status);
    if (status != NULL) {
      fail = 1;
    }
  }

  if (fail) {
    printf("At least one thread failed!\n");
    return 1;
  }
  printf("Main completed\n");
  return 0;
}

但我不断收到“错误:‘pthread_delay_np’未在此范围内声明”。有人知道为什么吗?

另外,还有其他方法可以防止线程在 thread_create 之后立即启动吗?跟调度器有什么关系?

提前谢谢你!!

【问题讨论】:

    标签: c++ linux posix


    【解决方案1】:

    引用some mailing list:

    它也可用于 HP-UX、VMS 和 Tru64 UNIX。 pthread_delay_np() 起源于 POSIX.1c 标准的 D4 草案。 POSIX.1c D4 的主要实现者是分布式计算环境 (DCE) 的 OSF。后缀 _np 表示 API 是不可移植的,不能依赖于在另一个平台上可用。通常nanosleep() 是您想要使用的替代品。

    【讨论】:

      【解决方案2】:

      只需改用nanosleep(2)

      【讨论】:

        【解决方案3】:

        看来pthread_delay_np 是一个非标准、不可移植(因此有“_np”后缀)的函数。您确定它存在于您的平台吗?

        【讨论】:

        • 嗯...显然它在我的平台上不存在。 :( 那么,我该怎么做才能防止线程在 thread_create 之后立即启动?
        • @delay:正如其他答案所说,您应该可以使用nanosleep
        【解决方案4】:

        您可以使用信号量向线程指示它可以在信号量等待点之后开始执行。

        答案可能取决于您通过避免立即启动线程来尝试实现的目标。

        编辑

        但是,我很确定固定延迟不是您真正需要的,除非您正在与环境(例如硬件)交互或只是在试验。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-06
          • 1970-01-01
          • 2019-10-30
          • 2012-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多