小编fgs*_*gts的帖子

为什么'typedef struct'在C中没有被选中?

在C中,可以定义struct,typedefed,并声明为:

typedef struct {
    int bar;
} Foo;
Foo foo;
Run Code Online (Sandbox Code Playgroud)

要么:

struct Foo {
    int bar;
} foo;
typedef struct Foo Foo;
Run Code Online (Sandbox Code Playgroud)

我认为这有点不一致,而且过于冗长.我希望它能像C++一样工作.

在C++中,您不需要指定typedef struct Foo Foo;能够声明结构Foo foo;而不是struct Foo foo;.为什么没有将它引入C标准或作为编译器标志选项?是否有任何C代码的例子如果typedef struct在C中被选为可选的话会破坏?

c standards struct typedef

1
推荐指数
1
解决办法
267
查看次数

pthread_cond_timedwait立即返回ETIMEDOUT

我试图用pthread_cond_timedwait等待Java的超时等待wait(long timeout, int nanos).我知道Java wait使用相对超时,而pthread_cond_timedwait使用绝对时间阈值.尽管考虑到这一点,pthread_cond_timedwait似乎立即返回错误代码ETIMEDOUT.

下面的示例程序打印一个值<0.我希望它打印一个值> = 0.

我使用pthread_cond_timedwait不正确吗?如何重写以下程序以添加例如5秒的延迟?

#define _POSIX_C_SOURCE 199309L

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

int main(void) {
    pthread_mutex_t mutex;
    pthread_cond_t cond;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_mutex_lock(&mutex);

    struct timespec t1;
    struct timespec t2;

    clock_gettime(CLOCK_MONOTONIC, &t1);

    t1.tv_sec += 5;

    while(pthread_cond_timedwait(&cond, &mutex, &t1) != ETIMEDOUT);

    clock_gettime(CLOCK_MONOTONIC, &t2);

    printf("%d", t2.tv_sec - t1.tv_sec);

    pthread_mutex_unlock(&mutex);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c c++ multithreading posix pthreads

0
推荐指数
1
解决办法
1087
查看次数

标签 统计

c ×2

c++ ×1

multithreading ×1

posix ×1

pthreads ×1

standards ×1

struct ×1

typedef ×1