Kutib turuvchi piter qanday qilib o'ldiriladi

Vaziyat o'zgaruvchini kutib turib uyquga ketgan piter. Ichki datchikda ishlaydigan booleanni ishlataman. Men ko'rgan muammom - ipning o'lishi bu o'zgaruvchini o'zgartirganda.

Men asboblarni ko'zdan kechirdim va ipni boshlasam, o'lishni ayting, keyin yangisini boshlang, mening iplarim soni 2 emas.

Qanday qilib men xohlagan bu ishni to'g'ri tarzda yo'q qilishim mumkin?

int worktodo=0;
BOOL runthread=NO;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;


void *threadfunc(void *parm)

{
    int rc;


    while(runthread==YES)

    {
        rc=pthread_mutex_lock(&mutex);

        while(!worktodo)

        {
            printf("thtread blocked\n");
            rc=pthread_cond_wait(&cond, &mutex);

        }

        printf("thtread awake.... doing work\n");

       //doing work

        worktodo=0;

        rc=pthread_mutex_unlock(&mutex);



    }

   //never reaches here!!
    pthread_detach(NULL);


}



void makeThread()
{

pthread_attr_t  attr;

int             returnVal;

returnVal = pthread_attr_init(&attr);
assert(!returnVal);
runthread=YES;
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);

int     threadError = pthread_create(&str->thread, &attr, &threadfunc, NULL);

returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
   //Report an error.
}



}

void wakethread()
{

    pthread_mutex_lock(&mutex);

    worktodo=1;
    pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);

}

void killthread

{
  runthread=NO;

}
0

2 javoblar

thiton to'g'ri edi. Men to'siq qo'yilgan paytda ipni o'ldira olmadim. Ehtimol, buni amalga oshirishning eng yaxshi usuli, lekin men uchun ishlaydigan yechim ishlov berishni noto'g'ri deb belgilash, keyin esa ipni uyg'otish edi.

void killthread

{
  runthread=NO;

  pthread_mutex_lock(&mutex);

    worktodo=1;
    pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);


}
1
qo'shib qo'ydi

Siz "runthread" ni "NO" deb o'zgartirasiz va "YES" ga solishtiring. Ip uning ichki qismiga hech qachon etmasligi kerak

while(runthread==YES)

pastadir. Bundan tashqari, ish zarrachalari ishlash uchun kutilgandan keyin, qotishmaxot uni uyg'otmaydi, va runthread ishni kutish davrida qoladi.

0
qo'shib qo'ydi
Men javobni aniqladim, men runthread o'rnatishni tashlab qo'ydim. O'ylaymanki, men keyinchalik kutib turgan ipni qanday o'ldirishni bilishim kerak
qo'shib qo'ydi muallif dubbeat, manba