Reputation: 605
I am learning threads and trying to implement a code which creates a thread. The thread writes into a file. If the thread has been created it returns 0
. The code here returns 0
but it does go into the function write()
but does not writes in the file . Just to check it goes in the function i have put a printf()
statement.I want the input should be taken by command line here but it also does not work so to make it simpler i have written only "hello world" to the file .
Here is the code :-
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *write(void *arg)
{
printf("HI \n");
FILE *fp;
fp = fopen("file.txt", "a");
if (fp == NULL) {
printf("error\n");
} else {
fprintf(fp, "hello world");
}
}
int main()
{
pthread_t thread;
int tid;
tid = pthread_create(&thread, NULL, write, NULL);
printf("thread1 return %d \n", tid);
exit(0);
}
Upvotes: 0
Views: 127
Reputation: 10254
I think you shoudl this code:
#include <thread>
#include <fstream>
using namespace std;
void write(string filename)
{
ofstream outfile(filename);
outfile<<"Hello World!"<<endl;
outfile.close();
}
int main()
{
thread t(write, "file.txt");
t.join();
}
use this command to compile the code:g++ -g -std=c++11 test.cpp -lpthread
Upvotes: 0
Reputation: 70392
You need to join with the thread to wait for it to finish before exiting your main program.
tid=pthread_create(&thread,NULL,write,NULL);
printf("thread1 return %d \n",tid);
pthread_join(thread, NULL);
exit(0);
Your thread function should return a value since it is declared to do so. Returning NULL is fine.
Upvotes: 2
Reputation: 5155
I suspect what's happening is the exit() call is executing before the fprintf() gets to the point of putting content into the buffer.
pthread_create() returns after creating the thread, not after the thread finishes, and then both threads run simultaneously. Maybe this is your first "race condition"?
void *result; pthread_join(tid, &result);
will wait for the function running in the other thread to return (and get it's return value).
correction Forgot that the file pointer is not automatically closed, so this will thwart you as well. Call fflush() or fclose() after the fprintf.
Upvotes: 3