I just learn the bare bone of making a thread inside a program using process.h in C programming. And now, my problem is how to stop a specific thread.
Here is my code:
#include <stdio.h>
#include <windows.h>
#include <process.h>
void mimicCounter( void * );
int main()
{
int i;
printf( "Now in the main() function.\n" );
_beginthread( mimicCounter, 0, (void*)12 );
for(i = 2; i <= 10; i++){
Sleep(500);
printf("%d\n",i);
}
system("PAUSE");
printf("\n");
}
void mimicCounter( void *arg )
{
int i;
printf( "The mimicCounter() function was passed %d\n", (INT_PTR)arg ) ;
for(i = 1; i <= 10; i++){
Sleep(500);
printf("%d\n",i);
}
}
I just want to stop the thread that I have created (the mimicCounter function) when it reaches i = 5, (yeah I know I set it to 10 but this is for ending a thread demo).
Thank you so much :)
The _endthread and _endthreadex functions terminate a thread created by _beginthread or _beginthreadex, respectively. You can call _endthread or _endthreadex explicitly to terminate a thread; however, _endthread or _endthreadex is called automatically when the thread returns from the routine passed as a parameter to _beginthread or _beginthreadex. Terminating a thread with a call to endthread or _endthreadex helps to ensure proper recovery of resources allocated for the thread.
From http://msdn.microsoft.com/en-us/library/aa246804(v=vs.60).aspx
Related
I'm new to C programming. In my main.c file I declare a global variable and initialize it to 0. This variable will run in pthread function and there it should be updated so I can reuse it main function again.
static int gResult = 0;
void* pthreadTask(){
gResult= readValue(); // It gives 1. gResult should be 1 now.
// But it gives 0.
}
int main(){
if(gResult == 1)printf("Passed test");
}
The problem looks like is that the thread is created but it is not scheduled immediately. So, the thread doesn't run any code and before that you check the value of your global variable. Try checking the variable after your thread has finished running. So, check the variable after pthread_join(). Do not use pthread_exit(). Try the following code (I tried it and it works):
#include <stdio.h>
#include <pthread.h>
static int gRes0 = 0;
static void *pthreadTask5(void* ctx)
{
gRes0 = 1;
printf("Value of gRes0 in thread = %d\n", gRes0);
}
int main(void)
{
pthread_t pt;
pthread_create(&pt, NULL, pthreadTask5, NULL);
// join pthread.
pthread_join(pt, NULL);
printf("Value of gRes0 in main = %d\n", gRes0);
return 0;
}
I once watched a movie called "War Games". I wanted to emulate that program in the movie. I wrote a simple program that can print and then speak the sentence, or the other way around. I want the program to execute both at the same time. How do I do that?
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <Windows.h>
#include <sapi.h>
ISpVoice *pVoice = NULL;
void printSmoothly(wchar_t *Str);
int main(void)
{
if (FAILED(::CoInitialize(NULL)))
return FALSE;
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL,
IID_ISpVoice, (void **)&pVoice);
wchar_t *sentence = L"Greetings professor falken,What would you like to do ?";
// how can i execute these two at the same time ?
printSmoothly(sentence);
pVoice->Speak(sentence, 0, NULL);
pVoice->Release();
CoUninitialize();
return 0;
}
void printSmoothly(wchar_t *Str)
{
size_t len = wcslen( Str ) , n ;
for( n = 0 ; n < len ; n++ )
{
wprintf( L"%c", Str[n] );
Sleep(50);
}
}
You want the speaking to be asynchronous.
Fortunately, Speak has a flag for that, so you don't need to dig into multiprocessing yet:
pVoice->Speak(sentence, SPF_ASYNC, NULL);
printSmoothly(sentence);
Note that you need to start the speech first, or it won't start until the printing has finished.
You'll also need to take care that you don't Release and CoUninitialize until the speaking has finished.
This will happen if you print faster than the speech, for instance.
(Asynchronous programming is much harder in reality than it is in Hollywood.)
I m doing thread programming and trying to implement MonteCarlo technique for calculating Pi value in it. I compiled the code and I have no error but when I execute I get no output for it. Kindly correct me if there's any mistake.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define frand() ((double) rand() / (RAND_MAX))
#define MAX_LEN 1353
const size_t N = 4;
float circlePoints=0;
void* point_counter(void *param){
float xcord;
float ycord;
while(MAX_LEN){
xcord=frand();
ycord=frand();
float cord = (xcord*xcord) + (ycord*ycord);
if(cord <= 1){
circlePoints++;}
}
}
int main()
{
printf("out");
size_t i;
pthread_t thread[N];
srand(time(NULL));
for( i=0;i <4;++i){
printf("in creating thread");
pthread_create( &thread[i], NULL, &point_counter, NULL);
}
for(i=0;i <4;++i){
printf("in joining thread");
pthread_join( thread[i], NULL );
}
for( i=0;i <4;++i){
printf("in last thread");
float pi = 4.0 * (float)circlePoints /MAX_LEN;
printf("pi is %2.4f: \n", pi);
}
return 0;
}
You're hitting an infinite loop here:
while(MAX_LEN){
Since MAX_LEN is and remains non-zero.
As to why you see no output before that, see Why does printf not flush after the call unless a newline is in the format string?
You have an infinite loop in your thread function:
while(MAX_LEN){
...
}
So all the threads you create never come out that loop.
Also, circlePoints is modified by all the threads which will lead to race condition ( what's a race condition? ) and likely render the value incorrect. You should use a mutex lock to avoid it.
while(any_non_zero_number_which does_not_update)
{
infinite loop //not good unless you intend it that way
}
I'm new here, and also I'm relatively new in programming in general. I' ve writen a program in C and I need to accelerate it using pthreads. I've tried to do so using OpenMP, but I don't know how to debug it. Also I need to find out if the programm is faster using pthreads and the times, but I don't know how to write this in my code. Here is my code
enter code here
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define NTHREADS 2
#define FYLLO(komvos) ((komvos) * 2 + 1)
long factorial(long);
void heap_function (int [], int, int );
void make_heap(long [], int );
void pop_heap(long [], int );
struct thread_data
{
long int n;
long int k;
long *b;
};
main()
{
long int n,k,c,fact=1;
long *a,*b,*d,p[k];
int i,j,rc;
int q[]={2,3,4,5,6,7,8,9,12,13,14,15,16};
pthread_t thread[NTHREADS];
struct thread_data threada;
for(i=0;i<NTHREADS;i++)
{
threada.n=n;
threada.k=k;
threada.b=b;
pthread_create (&thread[i], NULL, (void *)&threada);
}
for (i=0; i<NTHREADS; i++)
rc = pthread_join (thread[i], NULL);
for(i=0;i<13;i++)
{
k=pow(2,q[i])-1;
if(a=(long*)malloc(i*sizeof(long))==NULL);
{
printf("Den yparxei diathesimi mnimi gia desmeusi\n");
exit(1);
}
a[i]=k;
for(a[0];a[13];a[i]++)
{
n=(pow(2,q[i]))*k;
if(d=(long*)malloc((i*i)*sizeof(long))==NULL);
{
printf("Den yparxei diathesimi mnimi gia desmeusi\n");
exit(1);
}
d[i]=n;
}
c=(factorial(n))/((factorial(k))*(factorial(n-k)));
}
if(b=(long*)malloc(((i*i)+i)*sizeof(long))==NULL)
{
printf("Den yparxei diathesimi mnimi gia desmeusi\n");
exit(1);
}
for(i=0;i<13;i++)
{
b[i]=a[i];
}
for(i=13;i<182;i++) /* Gia i=13 exoume i^2=169 kai i^2+i=182*/
{
b[i]=d[i];
}
long heap[sizeof(b)];
make_heap( heap, sizeof(b) );
printf("To heap einai:\n");
for ( i = sizeof(b); i >=0; i-- )
{
printf( "%d ", heap[0] );
pop_heap( heap, i );
}
for(i=(n-k);i<=n;i++)
for(j=0;j<k;j++)
{
p[j]=heap[i];
printf("Ta %d mikrotera stoixeia eina ta %ld\n",k,p[j]);
}
free((void*)b);
getch();
}
long factorial(long n)
{
int a;
long result=1;
for( a=1;a<=n;a++ )
result=result*a;
return(result);
}
void heap_function( int a[], int i, int n )
{
while ( FYLLO( i ) < n ) /* Vazoume sto heap ta stoixeia san ypodentra */
{
int fyllo = FYLLO( i );
if ( fyllo + 1 < n && a[fyllo] < a[fyllo + 1] ) /* Dialegoume to maegalytero apo ta dyo paidia komvous */
++fyllo;
if ( a[i] < a[fyllo] ) /* Metaferoume to megalytero komvo sti riza */
{
int k = a[i];
a[i] = a[fyllo];
a[fyllo] = k;
}
++i; /* Synexizoume ston epomeno komvo */
}
}
void make_heap( long a[], int n ) /*Dhmioyrgoume ti sinartisi make_heap gia na mporesoume na valoume ta
stoixeia pou dwsame mesa sto heap kai na ta ta3inomisoume*/
{
int i = n / 2;
while ( i-- > 0 )
heap_function( a, i, n );
}
void pop_heap( long heap[], int n ) /*Dhmiourgoume ti sinartisi pop_heap gia na mporesoume na e3agoume
ta stoixeia apo to heap apo to megalytero sto mikrotero*/
{
long k = heap[0];
heap[0] = heap[n];
heap[n] = k;
heap_function( heap, 0, n ); /*Afou emfanistei to prwto stoixeio kaloume ti sinartisi heap_function
gia na ta3inomisei ta stoixeia pou menoun sto heap*/
}
Sorry for my messed up mail, but I'm new her now I'm getting to use it
Adding threads may not accelerate your program, it lets you do organize your work into execution units which can appear to run in parallel (and on multi-core systems, generally can run in parallel). If you're not on a multi-core system you can still gain an advantage if one or more of your threads must block waiting for slow input because other thread(s) can continue to run; this may or may not give you a faster runtime, depending on your actual program.
Debugging threads is generally more difficult than debugging a single thread, and how to do it comes down to the tools you have available. If your debugger is not able to make the job easier for you, I would recommend you first make your program run serially -- still break it up using a threaded model, but let the code for each run in the primary thread and let it run till completion, if your model permits this. Many threaded applications cannot be written like that because threads depend on each other during runtime, but it just depends on what you're doing exactly.
Now to your specific situation -- you're diving into the deep end when you don't know how to swim yet. I would suggest you first learn to use threads without the complexity of why you need them, otherwise you're making the problem more complicated than it needs to be. http://cs.gmu.edu/~white/CS571/Examples/Pthread/create.c has a simple example to get started with. Take particular notice to the parameters of the pthread_create() call and compare to what you've done; your code is missing the 3rd parameter -- the function to run as a thread. You appear to have no such function at all, and instead you seem to believe that the code following the call to pthread_create() is what runs in parallel. This is how fork() works, but that's very different.
That should be enough to get you started. http://cs.gmu.edu/~white/CS571/Examples/pthread_examples.html has additional examples, and a google of "pthread tutorial" would probably be helpful.
is there anyway to duplicate some static variable each time a thread make access to them?
I post a simple example:
Module testF.c
#define <stdio.h>
#include <windows.h>
#include <process.h>
#include "testF.h"
#define MAX_THREADS 10
int *var;
void testF( void *arg ){
int a,N,i;
a = (INT_PTR)arg;
N = (int)(10000/(int)(a+1));
var = (int*) malloc(N*sizeof(int));
for(i = 0; i<N; i++)
var[i] = (int)a;
_endthread();
}
...
And in another module main.c,
...
#include "testF.h"
int main(void){
HANDLE hth[MAX_THREADS];
DWORD dwExitCode;
int i;
for(i = 0; i<MAX_THREADS; i++)
hth[i] = (HANDLE)_beginthread( testF, 0, (void*)i );
WaitForMultipleObjects(MAX_THREADS, hth, TRUE, INFINITE);
for(i = 0; i<MAX_THREADS; i++){
GetExitCodeThread( hth[i], &dwExitCode );
printf( "thread 1 exited with code %u\n", dwExitCode );
CloseHandle( hth[i] );
}
}
In the this example the variable i would like to duplicate is *var.
I've seen that functions like rand() give always the same result if called from different thread, so I think that there should be a way to do it.
Thread-local storage.
Functions like rand() generally use thread local storage to maintain intercall state on a per-thread basis. This is what you would need to do instead of using a language construct like static. Your other option is to supply the variable into the thread start function, instead of using a global or static.