如何将两个程序转换为多线程进程

时间:2015-01-30 06:35:04

标签: c linux multithreading unix

我有这两个程序:

/* system.c*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define OUTPUTNAME "write.out"
main()
{
    long i;
    int fd;

    if ((fd=open(OUTPUTNAME,O_WRONLY|O_CREAT,0644)) <  0) {
        fprintf(stderr,"Can't open %s.  Bye.\n",OUTPUTNAME);
        exit(1);
    }
    for (i=0; i<50000; i++)  { /* write 50,000 Ys with write */
        if (write(fd,"Y",1) < 1) {
            fprintf(stderr,"Can't write. Bye\n");
            exit(1);
        }
    }
    close(fd);
    exit(0);
}

和..

/* library.c*/
#include <stdio.h>
#define OUTPUTNAME "fprint.out"
main()
{
    long i;
    FILE *fp;

    if ((fp=fopen(OUTPUTNAME,"w")) == NULL) {
        fprintf(stderr,"Can't open %s.  Bye.\n",OUTPUTNAME);
        exit(1);
    }
    for (i=0; i<400000; i++) {  /* write 400,000 Xs with fprintf */
        if (fprintf(fp,"X") < 1) {
            fprintf(stderr,"Can't write. Bye\n");
            exit(1);
        }
    }
    fclose(fp);
    exit(0);
}

我想将它们转换为多线程进程,以便进程同时启动两个步骤。我怎么做?我对此很新。

1 个答案:

答案 0 :(得分:0)

使用pthread创建两个线程,然后按如下方式运行它们,

gcc myProgram.o -o myProgram -lpthread

有关详细信息,请查看此article