Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "queue.h"
- #include <pthread.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define TIME_UNIT 100 // In microsecond
- static struct pqueue_t in_queue; // Queue for incomming processes
- static struct pqueue_t ready_queue; // Queue for ready processes
- static int load_done = 0;
- static int timeslot; // The maximum amount of time a process is allowed
- // to be run on CPU before being swapped out
- // Emulate the CPU
- void * cpu(void * arg) {
- int timestamp = 0;
- struct qitem_t* front = in_queue.head;
- int cnt = 0;
- while (front != NULL) {
- front = front->next;
- ++cnt;
- }
- front = in_queue.head;
- int size = 0; // bien dem
- struct pcb_t * arr = (struct pcb_t*)malloc(sizeof(struct pcb_t) * cnt);
- while (front != NULL) {
- arr[size] = *(front->data);
- front = front->next;
- ++size;
- }
- //////////////SORT
- int flag = 0;
- for (int i = 0; i < cnt-1; i++)
- {
- flag = 0;
- for (int j = 0; j < cnt-i-1; j++)
- {
- if (arr[j].arrival_time > arr[j+1].arrival_time)
- {
- struct pcb_t temp;
- temp = arr[j];
- arr[j] = arr[j+1];
- arr[j+1] = temp;
- flag = 1;
- }
- }
- if (flag == 0) break;
- }
- for (int i = 0; i < cnt; ++i)
- {
- int start = timestamp;
- int id = arr[i].pid;
- int exec_time = arr[i].burst_time;
- usleep(exec_time * TIME_UNIT);
- /* Update the timestamp */
- timestamp += exec_time;
- printf("%2d-%2d: Execute %d\n", start, timestamp, id);
- }
- ////////////////////END SORT
- }
- /* Read the list of process to be executed from stdin */
- void load_task() {
- int num_proc = 0;
- scanf("%d %d\n", ×lot, &num_proc);
- int i;
- for (i = 0; i < num_proc; i++) {
- struct pcb_t * proc = (struct pcb_t *)malloc(sizeof(struct pcb_t));
- scanf("%d %d\n", &proc->arrival_time, &proc->burst_time);
- proc->pid = i;
- en_queue(&in_queue, proc);
- }
- }
- int main() {
- pthread_t cpu_id; // CPU ID
- /* Initialize queues */
- initialize_queue(&in_queue);
- initialize_queue(&ready_queue);
- /* Read a list of jobs to be run */
- load_task();
- /* Start cpu */
- pthread_create(&cpu_id, NULL, cpu, NULL);
- pthread_join(cpu_id, NULL);
- pthread_exit(NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement