0

此代码是创建 20 个线程。每个线程生成一个随机字符串并以字母方式对其进行排序。我想要的是如下的同步结果

'##########线程#1开始##########'

'##########线程#2开始##########'

'##########线程#3开始##########'

……

'##########线程#19开始##########'

并遵循如下线程关键部分

[0] abcdcdf -> abcdefg

[1] abcdcdf -> abcdefg

[2] abcdcdf -> abcdefg

......

[19] abcdcdf -> abcdefg

线程编号的顺序可以混合,但不能省略或重叠。并且每个部分都应该被划分(Thread#n starting and [n] abvdffd -> abcddes)

这段代码应该实现什么组件?如果向我展示升级后的代码,您将非常慷慨

#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
#include <semaphore.h>
#define num_thread 20

char str[11];   //Global variable shared to threads                                                            
void *thread_work(void *tid);//Main body of Thread Working
void generate_str(int n);       //Create a random character array
void str_sort(int n);   //Sorting the char array alpabetically
void check_sort(void);
void print_time(struct timespec *myclock);    
void print_time_start(struct timespec *myclock);  
void print_time_end(struct timespec *myclock);
sem_t my_sem;

int main(void)
{
    pthread_t tid[num_thread];
    int ret; 
    int t;
    struct timespec myclock[2];
    srand(time(NULL));     //changes string value of each execution of program
    ret = sem_init(&my_sem, 0, 1);
    clock_gettime(CLOCK_REALTIME, &myclock[0]);
    print_time_start(myclock);  
        for(t=0; t<num_thread; t++)
        ret = pthread_create(&tid[t], NULL, thread_work, (void *)&t);

    for(t=0; t<num_thread; t++)
        ret = pthread_join(tid[t], NULL);

    clock_gettime(CLOCK_REALTIME, &myclock[1]);
    print_time_end(myclock);

    sem_destroy(&my_sem);
    return 0;
}

void *thread_work(void *t)
{
    int n = *((int *)t);
    struct timespec myclock[2]; 
    printf("########## Thread #%d starting ########## \n",n);

    sem_wait(&my_sem);  //Entry Section

    clock_gettime(CLOCK_REALTIME, &myclock[0]);   //Critical Section Start  
    generate_str(n);
    str_sort(n);
    check_sort();
    clock_gettime(CLOCK_REALTIME, &myclock[1]);
    print_time(myclock);              //Critical Section End

    sem_post(&my_sem);  //Exit Section

}

4

1 回答 1

0

请进行以下更改

  1. #include<unistd.h> //for usleep(1);

  2. for(t=0 ; t < num_thread; t++)
    {
    //pass the value of t insted of address
    ret = pthread_create(&tid[t], NULL, thread_work, (void *)t);
    usleep(1); //sleep is required to maintain the order of thread start;
    }

  3. int n = (int )t; //insted of int n = *((int *)t);,如果您在 pthread_create 中传递 t 的地址,则在线程获取调度时,主线程将更改 t 的值。

  4. 在线程创建循环之前锁定信号量sem_wait(&my_sem)并在线程创建循环之后解锁(sem_post(&my_sem))它main()

于 2013-05-08T09:17:21.350 回答