【问题标题】:is this the right way to initialize a semaphore with two threads [closed]这是用两个线程初始化信号量的正确方法吗[关闭]
【发布时间】:2016-06-28 11:05:18
【问题描述】:

我是使用信号量概念的新手。我要做的是将发送者和接收者集成到一个项目中,这样如果我运行该项目,发送者和接收者都会同时交换数据。以下是我尝试过的,但我的 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;
}

【问题讨论】:

  • @EOF 请看完整代码
  • 你不能编译代码,因为你必须在你的机器上安装 DDS。我只需要知道我们是否可以以这种方式初始化和使用信号量。这就是我先贴简单代码的原因。
  • 错误从这里开始 pthread_create(mythread2, NULL, (void*)receiver, NULL);在初始化信号量时
  • 好吧,让我直说吧。如果您可以向下滚动一下,我已经创建了两个线程 mthread1 和 mythread 2。我只想知道我是否可以像在上面的程序中那样创建 pthreads
  • 哈哈,这就是我之前试图向您展示的,我在哪里创建了一个信号量并进行了初始化、创建了线程并使用了一个 printf 函数

标签: c pthreads semaphore


【解决方案1】:

您似乎在函数“sender”的末尾缺少一个右大括号“}”。这应该解决您的特定错误“'receiver' undeclared”。

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    相关资源
    最近更新 更多