开发者

Why do I get "error: ‘pthread_delay_np’ was not declared in this scope"?

开发者 https://www.devze.com 2023-01-27 16:14 出处:网络
I was trying to see if it is possible to avoid a thread from starting immediately after thread_create. So, I came across pthread_delay_np and I tried the example:

I was trying to see if it is possible to avoid a thread from starting immediately after thread_create. So, I came across pthread_delay_np and I tried the example:

#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")开发者_Python百科;
  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;
}

But I keep getting "error: ‘pthread_delay_np’ was not declared in this scope". Does anybody know why?

Also, is there any other way of preventing a thread from starting immediately after thread_create? Anything to do with scheduler?

Thank you in advance!!


Quoting from some mailing list:

It is also available on HP-UX, VMS and Tru64 UNIX. pthread_delay_np() originated in the D4 draft of the POSIX.1c standard. The main implementer of POSIX.1c D4 was OSF for Distributed Computing Environment (DCE). The suffix _np denotes that the API is non-portable and cannot be relied on to be available on another platform. Generally nanosleep() is what you want to use as a replacement.


Just use nanosleep(2) instead.


It appears that pthread_delay_np is a non-standard, non-portable (hence the "_np" suffix) function. Are you certain it exists for your platform?


You could use a semaphore to indicate to the thread that it can start executing past the semaphore wait point.

The answer would probably depend on what you are trying to achieve by avoiding the immediate start of the thread.

EDIT

However, I'm quite sure a fixed delay is not what you actually need, unless you are interacting with the environment (e.g. hardware) or just experimenting.

0

精彩评论

暂无评论...
验证码 换一张
取 消