这是用两个线程初始化信号量的正确方法

时间:2016-06-28 11:05:18

标签: c pthreads semaphore

我是新手使用信号量的概念。我想要做的是将发送者和接收者集成到一个项目中,这样如果我运行项目,发送者和接收者同时交换数据。下面是我尝试但我的Eclipse CDT IDE显示的 **error: ‘receiver’ undeclared (first use in this function) pthread_create(mythread2, NULL, (void*)receiver, NULL);**

任何帮助感谢。

sem_t semaphore;

void sender() {
    while (1) {
        sem_wait( & semaphore);
        printf("Hello from the sender!\n");
        sleep(1); /* do not run so fast! */
        /* Write any number of messages, re-using the existing string-buffer: no leak!!. */
        for (i = 1; i <= NUM_MSG; i++) {
            msg - > index = i;
            snprintf(msg - > content, MAX_MSG_LEN, "Message no. %d", msg - > index);
            printf("Writing message: %s\n", msg - > content);
            status = Chat_ChatMessageDataWriter_write(talker, msg, userHandle);
            checkStatus(status, "Chat_ChatMessageDataWriter_write");
            sleep(1); /* do not run so fast! */
        }
        sem_post( & semaphore);
        printf("hello before exit\n");
        //        pthread_exit(NULL);
        printf("hello  after exit\n");
        sleep(1);
    }
    void receiver() {
        while (0) {
            sem_wait( & semaphore);
            printf("Hello from the receiver!\n");
            while (!terminated) {

                status = Chat_ChatMessageDataReader_take(
                    chatAdmin,
                    msgSeq,
                    infoSeq,
                    DDS_LENGTH_UNLIMITED,
                    DDS_ANY_SAMPLE_STATE,
                    DDS_ANY_VIEW_STATE,
                    DDS_ALIVE_INSTANCE_STATE);

                checkStatus(status, "Chat_NamedMessageDataReader_take");

                for (i = 0; i < msgSeq - > _length; i++) {
                    Chat_ChatMessage * msg = & (msgSeq - > _buffer[i]);
                    printf("%s\n", msg - > content);
                    fflush(stdout);
                }
            }
            sem_post( & semaphore);

            status = Chat_ChatMessageDataReader_return_loan(chatAdmin, msgSeq, infoSeq);
            checkStatus(status, "Chat_ChatMessageDataReader_return_loan");

            /* Sleep for some amount of time, as not to consume too much CPU cycles. */
#ifdef USE_NANOSLEEP
            sleeptime.tv_sec = 0;
            sleeptime.tv_nsec = 100000000;
            nanosleep( & sleeptime, & remtime);
#elif defined _WIN32
            Sleep(100);
#else
            usleep(1000000);
#endif
        }
    }
}

int main(void) {
    -- -- -- -- -- -- -- -- -- -- -- --
    -- -- -- -- -- -- -- -- -- -- -- --
    -- -- -- -- -- -- -- -- -- -- -- --

    /* Use the changed policy when defining the ChatMessage topic */
    chatMessageTopic = DDS_DomainParticipant_create_topic(
        participant,
        "Chat_ChatMessage",
        chatMessageTypeName,
        history_topic_qos,
        NULL,
        DDS_STATUS_MASK_NONE);
    checkHandle(chatMessageTopic, "DDS_DomainParticipant_create_topic (ChatMessage)");

    /* Create a Publisher for the chatter application. */
    chatPublisher = DDS_DomainParticipant_create_publisher(participant, pub_qos, NULL, DDS_STATUS_MASK_NONE);
    checkHandle(chatPublisher, "DDS_DomainParticipant_create_publisher");

    /* Create a DataWriter for the ChatMessage Topic (using the appropriate QoS). */
    talker = DDS_Publisher_create_datawriter(
        chatPublisher,
        chatMessageTopic,
        DDS_DATAWRITER_QOS_USE_TOPIC_QOS,
        NULL,
        DDS_STATUS_MASK_NONE);
    checkHandle(talker, "DDS_Publisher_create_datawriter (chatMessage)");

    /* Initialize the chat messages on Heap. */
    msg = Chat_ChatMessage__alloc();
    checkHandle(msg, "Chat_ChatMessage__alloc");
    msg - > userID = ownID;
    msg - > index = 0;
    msg - > content = DDS_string_alloc(MAX_MSG_LEN);
    checkHandle(msg - > content, "DDS_string_alloc");

    snprintf(msg - > content, MAX_MSG_LEN, "Hi there, I will send you %d more messages.", NUM_MSG);

    printf("Writing message: %s\n", msg - > content);

    /* Register a chat message for this user (pre-allocating resources for it!!) */
    userHandle = DDS__FooDataWriter_register_instance(talker, msg);

    /* Write a message using the pre-generated instance handle. */
    status = DDS__FooDataWriter_write(talker, msg, userHandle);
    checkStatus(status, "Chat_ChatMessageDataWriter_write");
    /* Create a Subscriber for the MessageBoard application. */
    chatSubscriber = DDS_DomainParticipant_create_subscriber(participant, sub_qos, NULL, DDS_STATUS_MASK_NONE);
    checkHandle(chatSubscriber, "DDS_DomainParticipant_create_subscriber");
    /* Create a DataReader for the chatMessageTopic Topic (using the appropriate QoS). */
    chatAdmin = DDS_Subscriber_create_datareader(
        chatSubscriber,
        chatMessageTopic,
        DDS_DATAREADER_QOS_USE_TOPIC_QOS,
        NULL,
        DDS_STATUS_MASK_NONE);
    checkHandle(chatAdmin, "DDS_Subscriber_create_datareader");

    /* Print a message that the MessageBoard has opened. */
    printf("MessageBoard has opened: send ChatMessages \n\n");

    /* Allocate the sequence holders for the DataReader */
    msgSeq = DDS_sequence_Chat_ChatMessage__alloc();
    checkHandle(msgSeq, "DDS_sequence_Chat_NamedMessage__alloc");
    infoSeq = DDS_SampleInfoSeq__alloc();
    checkHandle(infoSeq, "DDS_SampleInfoSeq__alloc");

    //initializing the semaphore
    sem_init( & semaphore, 0, 1);
    pthread_t * mythread1;
    pthread_t * mythread2;
    mythread1 = (pthread_t * ) malloc(sizeof( * mythread1));
    mythread2 = (pthread_t * ) malloc(sizeof( * mythread2));
    //start the thread
    printf("Starting thread, semaphore is unlocked.\n");
    pthread_create(mythread1, NULL, (void * ) sender, NULL);
    pthread_create(mythread2, NULL, (void * ) receiver, NULL);
    getchar();
    sem_wait( & semaphore);
    printf("Semaphore locked.\n");
    getchar();
    printf("Semaphore Unlocked.\n");
    sem_post( & semaphore);
    getchar();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

看起来你在函数'sender'的末尾错过了一个右括号'}'。这应该解决您的特定错误“'接收者'未声明的”。

[另外,函数'receiver'中的“while(0){...}”构造是有问题的......]

我在回答时,请允许我提出以下建议:

1)锁定/同步问题(在本例中为信号量)与DDS(或任何其他数据通信机制)正交。 [如果你能在这样的论坛上寻求帮助时保持代码清洁和专注,你可能会取得更大的成功。]

2)DDS的一些实现(我只能专门针对CoreDX DDS)是线程安全的,因此不需要围绕API调用进行保护。 [您可能需要与特定的DDS供应商核实以确认这一点。]从这个示例中,我很难推断出您的应用程序逻辑是否需要锁定,但它似乎并不存在。