Threads in c, what am I missing here? - c

I'm trying to create a thread, and I cannot figure out what I am doing wrong here. It's very basic, I just want to make sure I can get the thread created before I delve into what I'll be doing in the thread. Here's my code.
//prog.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <pthread.h>
#include <stdbool.h>
#include <unistd.h>
int threadCount =0; //Global variable to hold our thread counter
//this is the function that gets called when a thread is created
void *threadCreate(void* arg){
printf("Thread #%d has been created\n", threadCount);
threadCount++;
int param = (int)arg;
printf("We were sent: %d\n", param);
printf("Now the thread will die\n");
threadCount--;
pthread_exit(NULL);
}
//main
int main(int argc, char *argv[]){
pthread_t tid;
int numski = 50;
int res;
res = pthread_create(&tid, NULL, threadCreate, (void*)numski);
if (res){
printf("Error: pthread_create returned %d\n", res);
exit(EXIT_FAILURE);
}
return 0;
}
I am compiling using the following command:
gcc -Wall -pthread -std=c99 prog.c -o Prog
And when I try to run it, I get no output at all.

Main is exiting right away, and therefore your process is dying right away. End it with pthread_join to wait for them. Here is one example I googled, which contains the following example code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}

Related

I am trying to create a new c file that is a modified version of another file, nosmp.c, while also adding semaphore system calls

This is the code I have so far for the newly modified version of nosmp.c.
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
lng t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
The code below is the old nosmp.c code:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
void* thread(void* arg)
{
printf("\n Entered.., %c\n", *((char*)arg));
//critical section
sleep(4);
printf("\n Just Exiting.., %c\n", *((char*)arg));
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,thread,"1");
sleep(2);
pthread_create(&t2,NULL,thread,"2");
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}
For the modified version of the code above, I am trying to figure out where I would add the semaphore system calls into their proper lines to ensure that two threads will enter the critical section in order.

macos - macOS's pthread PTHREAD_CANCEL_ASYNCHRONOUS not working

I am using the following code:
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void
clean(void *arg)
{
printf("thread clean: %ld\n", (unsigned long)arg);
}
void*
thread_template(void *arg)
{
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
pthread_cleanup_push(clean, (void*)pthread_self());
printf("thread: %ld\n", (unsigned long)pthread_self());
while ( 1 ) {}
pthread_cleanup_pop(0);
pthread_exit((void*)0);
}
int
main(int argc, char const *argv[]) {
pthread_t tid;
pthread_create(&tid, NULL, thread_template, NULL);
// waiting for 2 seconds
sleep(2);
pthread_cancel(tid);
pthread_join(tid, NULL);
}
It works fine both on FreeBSD 11 and Ubuntu 16,
outputs are like this:
thread: 1994462320
thread clean: 1994462320
But on macOS, it seems pthread_cancel() doesn't affect the thread, main thread blocks at pthread_join(), the clean function never execute(only the first row was output).
So, what happened to macOS's pthread? or any wrong with my code ?

Is pthread_join a must when using pthread in linux?

I an learning pthread and I have a few questions.
Here is my code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define NUM_THREADS 10
using namespace std;
void *PrintHello(void *threadid)
{
int* tid;
tid = (int*)threadid;
for(int i = 0; i < 5; i++){
printf("Hello, World (thread %d)\n", *tid);
}
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
int t;
int* valPt[NUM_THREADS];
for(t=0; t < NUM_THREADS; t++){
printf("In main: creating thread %d\n", t);
valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
The code runs well and I don't call pthread_join. So I want to know, is pthread_join a must?
Another issue, is:
valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
equal to:
rc = pthread_create(&threads[t], NULL, PrintHello, &i);
It is not. But you need either pthread_exit() or pthread_join().
Here you called pthread_exit(), thats why the child threads continue execution even after the main thread terminates.
If there is any need for the main thread to wait till the child threads complete execution, you can use pthread_join().

Threading in c and initgraph

This is a program I did but the problem I am facing is that its not giving any output. When I try to run one thread its running perfectly else it doesn't. I tried to output it directly in the terminal which is working perfectly but when I try to output in the window using initgraph its not working.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include<graphics.h>
struct myran
{
int x;
int y;
};
void *print_message_function( void *ptr );
main()
{
int gd=DETECT,gm=VGAMAX;
initgraph(&gd,&gm,NULL);
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
struct myran a,b,c,d;
a.x=10;
a.y=10;
b.x=20;
b.y=20;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) &a);
if(iret1)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
exit(EXIT_FAILURE);
}
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) &b);
if(iret2)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
exit(EXIT_FAILURE);
}
printf("pthread_create() for thread 1 returns: %d\n",iret1);
//printf("pthread_create() for thread 2 returns: %d\n",iret2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
while(!kbhit())
;
closegraph();
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
struct myran *ss;
ss=(struct myran *)ptr;
int `enter code here`x1,y1,x,y;
x1=ss->x;
y1=ss->y;
int i=0;
for(i=0;i<5;i++)
printf("%d \n", x1);
}

Creating Dynamic Threads in C

How do we create multiple thread during runtime in C programming language?
If we need to create same amount of thread as specified by the user how do we do it?
On Linux use pthreads
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
Check _beginthread for Windows and posix threads for linux
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
void *print()
{
printf("\nThread Created");
}
int main()
{
int ch,i;
pthread_t *t;
printf("Enter the number of threads you want to create : ");
scanf("%d",&ch);
t=(pthread_t *)malloc(ch * sizeof(pthread_t ));
for(i=0;i<ch;i++)
{
pthread_create(&t[i],NULL,print,NULL); //Default Attributes
}
for(i=0;i<ch;i++)
{
pthread_join(t[i],NULL);
}
}
This is the most basic code for creating threads during runtime in Linux OS using pthread library.
pthreads

Resources