简体   繁体   English

C:printf()与flockfile()线程不安全

[英]C : printf() not thread safe with flockfile()

I need to print some messages on screen, and my program is multiprocess and multithread. 我需要在屏幕上打印一些消息,并且我的程序是多进程和多线程的。 I used flockfile() , flock() and mutex, but some messages are overlapped. 我使用了flockfile()flock()和互斥锁,但是有些消息是重叠的。 I did also a basic test program, and the result is the same. 我也做了一个基本的测试程序,结果是一样的。 Why i cannot synchronize the output? 为什么我无法同步输出?

void my_printf() {
    int i;
    for (i=0; i<20000; ++i) {
        flockfile(stdout);
        printf("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n");
        fflush(stdout);
        funlockfile(stdout);
    }
}


int main()
{
    fork();
    fork();
    fork();
    my_printf();
    exit(0);
}

EDIT 编辑

@Joachim Pileborg I have tried to use sem_t semaphores, but i had the same result...strings are overlapped. @Joachim Pileborg我尝试使用sem_t信号量,但结果相同...字符串重叠。

struct my_struct {
    sem_t *t;
};

struct my_struct *create_shared_memory(void)
{
    struct my_struct *str;
    key_t key;
    int fd;

    key = ftok("/", '5');
    fd = shmget(key, sizeof(struct my_struct), IPC_CREAT|0666);
    str = shmat(fd, NULL, 0);
    str->t = sem_open("/my_sem", O_CREAT|O_EXCL, 0644, 1);

    return str;
}

void my_printf(struct my_struct *str){
    int i;
    for (i=0; i<20000; ++i) {
        sem_wait(str->t);
        printf("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n");
        sem_post(str->t);
        fflush(stdout);
    }
}


int main()
{
    struct my_struct *my = create_shared_memory();
    fork();
    fork();
    my_printf(my);

    exit(0);
}

The flockfile function is for locking for other threads , not processes. flockfile函数用于锁定其他线程 ,而不是进程。 If you want inter-process locking look at eg POSIX semaphores , especially the named ones. 如果要进行进程间锁定,请查看POSIX信号 ,尤其是命名的信号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM