Martini Martini - 1 month ago 13
C Question

C, error of compilation during using "usleep" function

I use Ubuntu Linux. When I try use "usleep" function, I get information about "implicit declaration of function usleep". Below is the error code:

muteks.c:70:4: warning: implicit declaration of function ‘usleep’ [-Wimplicit-function-declaration]
usleep(300);
^


Source code:

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

void * klientWatek (void* arg);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int lKf = 10;
int lKl = 15;

int main ()
{
pthread_t *klientTab;
int *klientTabId;
int lKr = 1;
int i;
// pamięć dla identyfikatora wątku
klientTab = (pthread_t *) malloc (lKl* sizeof (pthread_t));
klientTabId = (int *) malloc (lKl*sizeof (int)); //pamięć dla id
// będącego argumentem przekazywanym do funkcji
for (i=0; i<lKl; i++) klientTabId[i]=i; //przypisanie

printf("\nOtwieramy pub (simple)!\n");
printf("\nLiczba wolnych kufli %d\n", lKf);

for (i=0; i<lKl; i++)
{
pthread_create (&klientTab[i], NULL, klientWatek,
&klientTabId[i]);
}

for (i=0; i<lKl; i++)
{ //wątek joinable, ręcznie zwalniamy zasoby
pthread_join (klientTab[i], NULL);
}

printf("\nZamykamy pub!\n");
printf("\nLiczba wolnych kufli %d\n", lKf);

void * klientWatek (void * argWsk)//zostanie przekazany klientTabId[i]
{
int mojId = * ( (int *) argWsk);
int i,j;

int pobranoKufel = 0;
int ileMuszeWypic = 2;

printf ("\nKlient %d, wchodzę do pubu\n", mojId);

for (i=0; i<ileMuszeWypic; i++)
{
do
{
pthread_mutex_lock(&mutex);
if (lKf > 0)
{
printf("\nSprawdziłem, czy jest wolny kufel\n");
lKf--;
pobranoKufel = 1;
printf("\nWziąłem kufel\n");
}

pthread_mutex_unlock(&mutex);
} while (pobranoKufel == 0);
printf("\nKlient %d, wybieram kufel\n", mojId);

j=0;
printf("\nKlient %d, nalewam z kranu %d\n", mojId, j);
usleep(300);

printf("\nKlient %d, pije\n", mojId);
nanosleep((struct timespec[]){{0, 500000000L}},NULL);

printf("\nKlient %d, odkladam kufel\n", mojId);

if (pobranoKufel == 1)
{
pthread_mutex_lock(&mutex);
pobranoKufel=0;
lKf++;
pthread_mutex_unlock(&mutex);
}
}
printf("\nKlient %d, wychodzę z pubu\n", mojId);

return (NULL);
}


The way I tried to compile program:

gcc -Wall -pedantic -std=gnu99 -pthread muteks.c -o przyklad


What shall I do now, to compile that?

usr usr
Answer

usleep() is declared in the standard header unistd.h which you haven't included. Include it:

#include <unistd.h>

On a relevant note: usleep() has been removed since POSIX-2008 and recommends to use nanosleep() instead.