嗨,我正在编写一个将字符串写入文件的程序,进程1将在文件中写入一个小写字母,进程2在同一文件中写入一个大写字母。我使用线程实现了一个程序,必须首先运行进程1,然后再运行进程2。程序如下。

/******************
 *  Header Files
 ******************/
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

pthread_mutex_t lock;

void* write_p1()
{
    if((pthread_mutex_lock(&lock)) != 0)
    {
        printf("pthread_mutex_lock() failed\n");
        exit(1);
    }

    int index=0;    /*used in for loop*/
    int flag=0; /*flag used in capital letter and space detecion*/
    FILE *fp=NULL;  /*file pointer used to store open file*/
    char str[100];  /*to store user string*/

    printf("*****Hi, I am Process 1*****\n");
    /*open the sample.txt file for write*/
    fp=fopen("sample.txt","w");
    if(fp==NULL)
    {
        printf("Not able to open file\n");
        exit(1);
    }
    printf("Enter small letters\n");
    fgets(str,100,stdin);

    /*capital letter and space detection*/
    if((strlen(str)>0)&&(str[strlen(str)-1]=='\n'))
    {
        str[strlen(str)-1]='\0';
    }
    for(index=0;str[index]!='\0';index++)
    {
        if(islower(str[index]) || str[index] == ' ')
        {
            flag=0;
        }
        else
        {
            printf("Enter Small Letters\n");
            exit(1);
        }
    }
    if(flag==0)
    {
        fprintf(fp,"%s",str);
    }
    /*close the file*/
    fclose(fp);
    printf("Entered string: %s\n",str);

    if((pthread_mutex_unlock(&lock)) != 0)
    {
        printf("pthread_mutex_unlock() failed\n");
        exit(1);
    }
    printf("\n\n");
}

void* write_p2()
{
        if((pthread_mutex_lock(&lock)) != 0)
        {
                printf("pthread_mutex_lock() failed\n");
                exit(1);
        }

        int index=0;    /*used in for loop*/
        int flag=0;     /*flag used in small letter and space detecion*/
        FILE *fp=NULL;  /*file pointer used to store open file*/
        char str[100];  /*to store user string*/

    printf("*****Hi, I am Process 2*****\n");
        /*open the sample.txt file for write*/
        fp=fopen("sample.txt","a");
    if(fp==NULL)
        {
                printf("Not able to open file\n");
                exit(1);
        }
        printf("Enter Capital letters\n");
        fgets(str,100,stdin);

    /*capital letter and space detection*/
        if((strlen(str)>0)&&(str[strlen(str)-1]=='\n'))
        {
                str[strlen(str)-1]='\0';
        }
        for(index=0;str[index]!='\0';index++)
        {
                if(isupper(str[index]) || str[index] == ' ')
                {
                        flag=0;
                }
                else
                {
                        printf("Enter capital Letters\n");
                        exit(1);
                }
        }
        if(flag==0)
    {
                fprintf(fp,"%s",str);
        }
        /*close the file*/
        fclose(fp);
        printf("Entered string: %s\n",str);
        if((pthread_mutex_unlock(&lock)) != 0)
        {
                printf("pthread_mutex_unlock() failed\n");
                exit(1);
        }
        printf("\n\n");
}

int main(void)
{
    /*initialized semaphore*/
    if((pthread_mutex_init(&lock,NULL)) != 0)
    {
        printf("pthread_mutex_init() failed\n");
        exit(1);
    }
    /*create a two thread*/
    pthread_t t1=0,t2=0;
    pthread_create(&t1,NULL,write_p1,NULL);
    pthread_create(&t2,NULL,write_p2,NULL);
    /*this function wait for thread to terminate*/
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    /*destroy the semaphore*/
    if((pthread_mutex_destroy(&lock)) != 0)
    {
        printf("pthread_mutex_destroy() failed\n");
        exit(1);
    }
    return 0;
}


现在,该程序正在运行,但是有时它将运行第一个线程2(进程2)或某个时间运行线程1(进程1),对此我需要一个解决方案,它必须在该线程2(进程1)之后首先运行线程1(进程1)。 2),那么我该怎么做?

最佳答案

我正在为您准备以下节目。您可以通过使用条件变量来实现。在您的代码中实现相同的过程。如何运作?为了开始控制过程,我们首先允许线程1。在主线程中(即主函数;每个程序都有一个主线程,在C / C ++中,一旦控件通过内核传递给主方法/函数,操作系统就会自动创建该主线程),我们正在调用pthread_cond_signal(&cond1 );。从主线程调用此函数后,正在等待cond1的thread1将被释放,它将开始进一步执行。一旦完成其最终任务,它将调用pthread_cond_signal(&cond2);。现在,正在等待条件cond2的线程,即thread2,将被释放,它将开始执行其最后阶段

#include<pthread.h>


pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;

pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;


int TRUE = 1;


void * threadMethod1(void *arg)
{

  printf("In thread1\n");

  do{

    pthread_mutex_lock(&lock1);

    //Add your business logic(parallel execution codes)  here

    pthread_cond_wait(&cond1, &lock1);

    printf("I am thread1  generating the final report and inserting into file \n");

    pthread_cond_signal(&cond2);/* Now allow 2nd thread to process */

    pthread_mutex_unlock(&lock1);

  }while(TRUE);

  pthread_exit(NULL);

}



void * threadMethod2(void *arg)

{

  printf("In thread2\n");

  do

  {

    pthread_mutex_lock(&lock2);

    //Add your business logic(parallel execution codes)  here

    pthread_cond_wait(&cond2, &lock2);

    printf("I am thread2  generating the final report and inserting into a file \n");

    pthread_cond_signal(&cond1);

    pthread_mutex_unlock(&lock2);

  }while(TRUE);

  pthread_exit(NULL);

}

int main(void)

{

  pthread_t tid1, tid2;

  int i = 0;


  printf("Before creating the threads\n");

  if( pthread_create(&tid1, NULL, threadMethod1, NULL) != 0 )
        printf("Failed to create thread1\n");

  if( pthread_create(&tid2, NULL, threadMethod2, NULL) != 0 )
        printf("Failed to create thread2\n");

  pthread_cond_signal(&cond1);/* Now allow first thread to process first */


  sleep(1);

  TRUE = 0;/* Stop all the thread */

  //sleep(3);

  pthread_join(tid1,NULL);
  pthread_join(tid2,NULL);

 exit(0);

}

08-04 15:00