0

我只想将项目添加到队列中,并在队列中有东西时删除它们。我打算从堆栈中取出一些东西,然后等待 10 秒,然后再做一次。我只是不确定如何将它扔到线程中。我在 PuTTy 上使用 C。我有违抗的功能。不想复制 thme 以节省空间。delete() 只是删除第一个。我如何让线程暂停 10 秒。Sleep 实际上会暂停命令窗口。

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <conio.h>

#define MAXQUEUE 100

    struct queue 
    {
        char name[256];
        struct queue *link;
    };

void *thread_routine(void *arg) {
    int tr;
    while(tr!=0) {
        sleep(10);
        delete();
    }

}

struct queue *start=NULL;

int i=0;

void main() {

    pthread_t thread1;
    pthread_t thread2;
    void *thread_result;
    int status;
    status = pthread_create(&thread1, NULL, thread_routine, NULL);
    if (status != 0) {
        printf ("thread create failed\n");
        exit(1);
    }
    /* wait for the thread to finish */

    status = pthread_join(thread1, &thread_result);
    if (status != 0) {
        printf ("thread join failed\n");
        exit(1);
    }
    printf ("child thread finished: result = %d\n", (int) thread_result);

    int ch;
    while(ch!=4) {
        printf("\nSelect an option:\n");
        printf("1 to add an item to the queue\n");
        //printf("2 to delete an item from the queue\n");
        printf("3 to print the queue\n");
        printf("4 for Exit\n");
        scanf("%d",&ch);
        switch(ch) {
            case 1: 
                add();
                break;
            case 2: 
                delete();
                break;
            case 3: 
                print();
                break;
            case 4: 

                break;
            default:
                printf("Incorrect option\n");
                break;
        }
    }
}
4

2 回答 2

1

Sleep 实际上会暂停命令窗口。

那是因为您加入了线程,也就是等待它完成。保持线程分离,并可能为读取选项创建一个无限循环。

另外,我建议使用互斥锁和条件变量来通知线程何时插入新项目。这样做虽然“睡眠”方式应该可以工作,但它可能不会像您期望的那样立即删除该项目。

于 2013-08-06T03:11:13.463 回答
0

也许您可以使用警报信号,而sleep().不仅仅是为信号设置处理程序并确保没有线程阻塞它。

于 2013-08-06T03:15:55.107 回答