小编man*_*nut的帖子

如何同步线程?

我在这段代码中使用了线程.但是当我在shell中执行此代码时,某些线程没有打印此行.

printf("\ti'm %dth thread:)", j);  
printf("\t%c  %d  %d  %d \n", arr[j].op, arr[j].byte, seq, no_file);
Run Code Online (Sandbox Code Playgroud)

此外,甚至一些线程也会打印此行两次.这个过程发生了什么?以及如何重新组织此代码以便线程只打印一次线?

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>

typedef struct {char op; int byte; int seq; int no_file; } ARRAY; 

ARRAY *arr;

void *thread_operation(void *arg){
    int j =*((int*)arg);
    seq = arr[j].seq;
    int no_file = arr[j].no_file;
    printf("\ti'm %dth thread:)", j);
    printf("\t%c  %d  %d  %d \n", arr[j].op, arr[j].byte, seq, no_file);
}

int main()
{
    int err, j, i = …
Run Code Online (Sandbox Code Playgroud)

c unix synchronization pthreads

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

标签 统计

c ×1

pthreads ×1

synchronization ×1

unix ×1