Lab 5
Lab 5
Threading
A thread is a sequence of such instructions within a program that can be executed independently
of other code.
A. Identifying a thread
Each thread identified by an ID, which is known as Thread ID. Thread ID is quite different
from Process ID. A Thread ID is unique in the current process, while a Process ID is unique
across the system.
Thread ID is represented by type pthread_t
a) Header file(s)
The header file which needs to be included to access thread functions
#include<pthread.h>
Then, how to compile C program with pthread.h library?
To compile C program with pthread.h library, you have to put -lpthread just after the compile
command gcc thread.c -o thread, this command will tell to the compiler to execute program
with pthread.h library.
First set breakpoints on all thread functions; thread1, thread2, and main.
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
void* doSomeThing(void *arg)
{
unsigned long i = 0;
pthread_t id = pthread_self();
if(pthread_equal(id,tid[0]))
{
printf("\n First thread processing\n");
}
else
{
printf("\n Second thread processing\n");
}
for(i=0; i<(0xFFFFFFFF);i++);
return NULL;
}
int main(void)
{
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
{
printf("\n can't create thread :[%s]", strerror(err));
}
else
{
printf("\n Thread created successfully\n");
}
i++;
}
sleep(5);
return 0;
}
D. User Management:
1. Checking all/specific user accounts
$ lslogins < --user-accs/--system-accs>
$ lslogins <username>
Example: $ lslogins bilal
D. touch Command:
1. Create file using touch command
$ touch <-c> <filename1> <filename2> <filename3>
-c : to suppress creation if file does not exist
-t : to create file using specified date and time
Example: $ touch OSLab5.1 OSLab5.2
1. Create a file OSLabFile5.1 with date & time 25th January, 2025 3:00 PM.
2. Create a file OSLab5.4 dated 01 Jan 2024 and copy its date to OSLab5.1
4. Create a user as testuser, and then execute command for crearing file OSLabFile5.5
using testuser and shell /bin/bash
5. Creates 5 threads each thread prints a "Hello World!" message, and then terminates.
PROGRAM
using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
Console.WriteLine("Hello World!");
}
}
public class ThreadExample
{
public static void Main()
{
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
Thread t3 = new Thread(new ThreadStart(mt.Thread1));
Thread t4 = new Thread(new ThreadStart(mt.Thread1));
Thread t5 = new Thread(new ThreadStart(mt.Thread1));
t1.Start();
t2.Start();
t3.Start();
t4.Start();
t5.Start();
}
}
OUTPUT