Red de conocimiento informático - Material del sitio web - En el entorno Linux, lectura y escritura de subprocesos múltiples de un archivo de dispositivo (dos subprocesos son suficientes), por favor deme un programa simple.

En el entorno Linux, lectura y escritura de subprocesos múltiples de un archivo de dispositivo (dos subprocesos son suficientes), por favor deme un programa simple.

El archivo de configuración es conf.txt

El código de prueba es el siguiente. Preste atención a agregar el parámetro -lpthread al vincular

#include

#include //perror()

#include

#include / /sleep()

#include // time()

#include //rand()

# define FD "conf .txt"

typedef void *(*fun)(void *);

struct my_struct

{

unsigned time_to_wait;

int n;

};

void *test_thread(struct my_struct *);

int main (int argc , char const * argv[])

{

ARCHIVO *fp = fopen(FD, "r");

if (fp == NULL)

{

perror(FD);

return -1;

}

srand((sin firmar )time(NULL )); //Inicializar semilla aleatoria

int thread_count;

fscanf(fp, "%d", &thread_count);

fclose( fp);

if (thread_count <= 0)

{

printf("Thread_count <= 1, salga del programa.

\n");

return -1;

}

pthread_t *ptid = (pthread_t *)malloc(sizeof(pthread_t) * thread_count); / /Guardar ID del hilo

int i;

for (i = 0; i < thread_count; i++)

{

int tw = rand() % thread_count + 1; //Tiempo de espera aleatorio

struct my_struct * p = (struct my_struct *)malloc(sizeof(struct my_struct));

if (p == NULL)

{

perror("Error de asignación de memoria");

goto ERROR;

}

p->time_to_wait = tw;

p->n = i + 1;

int rval = pthread_create(ptid + i, NULL, (divertido) test_thread, ( void *)(p)); //Ten en cuenta las conversiones forzadas aquí (dos)

if (rval != 0)

{

perror( " Error al crear el hilo");

goto ERROR;

}

//sleep(1); //Esta oración se puede agregar o no. Sí. Esto se agregó originalmente para permitir una cierta diferencia de tiempo entre los dos hilos cuando comienzan

}

printf("El hilo principal comienza\n\n" );

fflush(stdout);

for (i = 0; i < thread_count; i++)

{

pthread_join( *(ptid + i), NULL); //Espera a que salgan todos los hilos.

}

printf("\nEl hilo principal salió\n");

ERROR:

free(ptid);

return 0;

}

void *test_thread(struct my_struct * p) //Función que se ejecuta cuando se inicia el hilo

{

printf("El hilo %d se inició y se espera que se ejecute durante %d segundos\n", p->n, p->time_to_wait);

fflush(stdout) ;

sleep(p->time_to_wait); //Deja que el hilo espere un rato

printf("El %d hilo termina\n", p->n);

fflush(stdout);

free(p);

return NULL;

}

Tu Segundo, te respondí en Baidu HI~