I'm fairly new to threads in C. For this program I need to declare a thread which I pass in a for loop thats meant to print out the printfs from the thread.
I can't seem to get it to print in correct order. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 16
void *thread(void *thread_id) {
int id = *((int *) thread_id);
printf("Hello from thread %d\n", id);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
int code = pthread_create(&threads[i], NULL, thread, &i);
if (code != 0) {
fprintf(stderr, "pthread_create failed!\n");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
//gcc -o main main.c -lpthread
That's the classic example of understanding multi-threading.
The threads are running concurrently, scheduled by OS scheduler.
There is no such thing as "correct order" when we are talking about running in parallel.
Also, there is such thing as buffers flushing for stdout output. Means, when you "printf" something, it is not promised it will happen immediately, but after reaching some buffer limit/timeout.
Also, if you want to do the work in the "correct order", means wait until the first thread finishes it's work before staring next one, consider using "join":
http://man7.org/linux/man-pages/man3/pthread_join.3.html
UPD:
passing pointer to thread_id is also incorrect in this case, as a thread may print id that doesn't belong to him (thanks Kevin)
Related
my problem is that I coded server/client application on windows. Now in debug mode everything works fine and as it should , but in release mode the server doesn´t receive or send messages.
I think it is due to that, that the for loop inside the infinite for loop doesn´t get accessed.I also tried to implement this solution with a while but it didn´t work. I think it might be the problem that i call a function in the condition field, because when i compare the i to an integer it gets accessed. Also interesting is that when i std::cout something right before the inner for loop , the loop gets also accessed , despite the fact that I am calling the function in the condition field.
#include <iostream>
#include <thread>
#include "server.cpp"
//gets defined in server.cpp
void server::acceptConn() {
u_long mode =1;
for(;;){
int len = sizeof(incAddr[connectedSocks]);
if((inc_sock[connectedSocks] = accept(serv,(struct sockaddr *)&incAddr[connectedSocks],&len))!= SOCKET_ERROR){
std::cout<<"client connected : "<<inet_ntoa(incAddr[connectedSocks].sin_addr)<<std::endl;
ioctlsocket(inc_sock[connectedSocks],FIONBIO,&mode);
connectedSocks++;
}
}
}
int main() {
server ser;
ser.init_Server();
std::thread t(&server::acceptConn,&ser);
char buf[1024];
for(;;){
for(int i=0 ; ser.getCounter()>i;i++){
if (recv(ser.getInc_Sock()[i], buf, sizeof(buf), 0) == SOCKET_ERROR) {
} else{
for (int x = 0; x < ser.getCounter(); x++) {
if(x==i){//just that the message doesnt get send back to the sender}
else{
if (send(ser.getInc_Sock()[x], buf, sizeof(buf), 0) == SOCKET_ERROR) {
std::cout<<"send failed : "<<WSAGetLastError()<<std::endl;
}
}
}
}
}
}
}
int getCounter(){return connectedSocks;};//in server.h
The result should be that Server is having a List of connected socks and is distributing the messages to everyone. Now when I am running it in debug mode everything works fine. What could be the problem?
Your code lacks any form of synchronization between the two threads. The worker thread writes data, and the main thread reads data. But because there is no synchronization between them (mutex/atomics/etc), every read from the main thread is a data race with the writes from the worker thread.
And data races are undefined behavior. So the compiler is permitted to compile the main thread as if nobody ever writes data.
When you put a std::cout in your loops, this "works" because std::cout requires some form of synchronization to keep multiple threads from writing to stdout at the same time. So you're effectively piggybacking off of that internal synchronization. But you shouldn't rely on that; you should instead use proper synchronization primitives.
I want to make a program that gets the ids from a database and create a thread with the same function for each id. It works, but when I add a while loop to the function it only hangs there and doesn't get the next id's.
My code is:
void foo(char* i) {
while(1){
std::cout << i;
}
}
void makeThreads()
{
int i;
MYSQL *sqlhnd = mysql_init(NULL);
mysql_real_connect(sqlhnd, "127.0.0.1", "root", "h0flcepqE", "Blazor", 3306, NULL, 0);
mysql_query(sqlhnd, "SELECT id FROM `notifications`");
MYSQL_RES *confres = mysql_store_result(sqlhnd);
int totalrows = mysql_num_rows(confres);
int numfields = mysql_num_fields(confres);
MYSQL_FIELD *mfield;
MYSQL_ROW row;
while((row = mysql_fetch_row(confres)))
{
for(i = 0; i < numfields; i++)
{
printf("%s", row[i]);
std::thread t(foo, row[i]);
t.join();
}
}
}
int main()
{
makeThreads();
return 0;
}
Output is:
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
Thanks
The for loop in question currently creates one thread object and one thread. Period. joining hides this problem in a way by forcing the main thread to wait for the thread to run to completion. That the thread can't is another issue.
Creating a thread and immediately joining forces your program to run sequentially and defeats the point of using threads. Not joining the thread will result in Bad because the thread object will be destroyed at the end of the loop and the thread has not been detached. Destroying an undetached thread is bad. std::terminate does pretty much what it sounds like it does: It hunts down and kills Sarah Connor. Just kidding. It ends your program with all the subtlety of a headsman's axe.
You could detach the threads manually by calling detach, but that's a really, really Bad Idea because you lose control of the thread and your program will exit while the threads are still running.
You need to store these threads and join them later, after the loop that spawns them.
Here's a simple approach to do that:
std::vector<std::thread> threads;
for(i = 0; i < numfields; i++)
{
std::cout << row[i];
threads.push_back(std::thread(foo, row[i]));
}
for (std::thread & t: threads)
{
t.join();
}
Now you will have numfields threads running forever, and I'm sure you can take care of that problem on your own.
t.join();
Means the program waits here for the thread t to finish.
Since:
t executes foo
foo never ends, due to while true
Then: you never execute the instructions after the join
So you have the uninterrupted 111111
I am learning multi-threading in Linux platform. I wrote this small program to get comfort with the concepts. On running the executable, I could not see any error nor does it print Hi. Hence I made to sleep the thread after I saw the output. But still could not see the prints on the console.
I also want to know which thread prints at run time. Can anyone help me?
#include <iostream>
#include <unistd.h>
#include <pthread.h>
using std::cout;
using std::endl;
void* print (void* data)
{
cout << "Hi" << endl;
sleep(10000000);
}
int main (int argc, char* argv[])
{
int t1 = 1, t2 =2, t3 = 3;
pthread_t thread1, thread2, thread3;
int thread_id_1, thread_id_2, thread_id_3;
thread_id_1 = pthread_create(&thread1, NULL, print, 0);
thread_id_2 = pthread_create(&thread2, NULL, print, 0);
thread_id_3 = pthread_create(&thread3, NULL, print, 0);
return 0;
}
Your main thread probably exits and thus the entire process dies. So, the threads don't get a chance to run. It's also possible (quite unlikely but still possible) that you'd see the output from the threads even with your code as-is if the threads complete execution before main thread exits. But you can't rely on that.
Call pthread_join(), which suspends the calling thread until the thread (specified by the thread ID) returns, on the threads after the pthread_create() calls in main():
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
You can also use an array of pthread_t which would allow you to use a for loop over the pthread_create() and pthread_join() calls.
Or exit only the main thread using pthread_exit(0), which would exit only the calling thread and the remaining threads (the ones you created) will continue execution.
Note that your thread function should return a pointer or NULL:
void* print (void* data)
{
cout << "Hi" << endl;
return NULL;
}
Not sure about the high sleeps either right the threads exit, which is unnecessary and would hold the threads from exiting. Probably not something you wanted.
I have a problem with the following code:
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
void f1(uint count)
{
while(count-- > 0)
{
// boost::this_thread::sleep(boost::posix_time::millisec(1000));
sleep(1);
}
}
void folkflore()
{
int res = fork();
//parent
if ( res )
{
wait(NULL);
}
else
{
unsigned int x = 2;
boost::thread tx(boost::bind(f1, 2));
tx.join();
_exit(-5);
}
}
int main()
{
std::cout << "Main program " << getpid() << std::endl;
unsigned int x = 2;
boost::thread t1(boost::bind(f1, 2));
boost::thread m(folkflore);
m.join();
t1.join();
return 0;
}
[LATER EDIT]
Ok, so it looks like boost::this_thread::sleep acquires a mutex in the behind-scenes, so I guess I'll stick with plain old sleep() which is plain old good for me.
[/LATER EDIT]
From main() I issue a t1 thread which counts 2 seconds and another thread which does the following: fork()'s inside it, the parent waits for the child and the child creates another thread which also counts 2 seconds.
The problem is that if I use boost::this_thread:sleep the program hangs or deadlocks somehow. If I use sleep(), then it works ok. Am I doing something wrong here? What is the difference between these two ?
From the man-page of sleep I get that:
"sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
"
Also from the boost docs, boost::this_thread::sleep seems to do the same thing.
You do dangerous things here:
fork call duplicates the whole program, but only one thread (current one) running
in new process. So all mutex here, but only one thread.
And if some thread lock mutexes and your thread try lock it in new process,
it will wait forever.
Here
boost::this_thread::sleep(boost::posix_time::millisec(1000));
if look at boost's include file, sleep looks like:
this_thread::sleep(get_system_time()+rel_time);
get_system_time call tz_convert from libc, which take mutex. And looks like before fork another thread lock it, and...
In the following code I create some number of threads, and each threads sleeps for some seconds.
However my main program doesn't wait for the threads to finish, I was under the assumption that threads would continue to run until they finished by themselves.
Is there someway of making threads continue to run even though the calling thread finishes.
#include <pthread.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
int sample(int min,int max){
int r=rand();
return (r %max+min );
}
void *worker(void *p){
long i = (long) p;
int s = sample(1,10);
fprintf(stdout,"\tid:%ld will sleep: %d \n",i,s);
sleep(s);
fprintf(stdout,"\tid:%ld done sleeping \n",i,s);
}
pthread_t thread1;
int main(){
int nThreads = sample(1,10);
for(int i=0;i<nThreads;i++){
fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
pthread_detach(thread1);
}
// sleep(10);//work if this is not commented out.
return 0;
}
Thanks
Edit:
Sorry for not clarifying, is it possible without explicitly keeping track of my current running threads and by using join.
Each program has a main thread. It is the thread in which your main() function executes. When the execution of that thread finishes, the program finishes along with all its threads. If you want your main thread to wait for other threads, use must use pthread_join function
You need to keep track of the threads. You are not doing that because you are using the same thread1 variable to every thread you are creating.
You track threads by creating a list (or array) of pthread_t types that you pass to the pthread_create() function. Then you pthread_join() those threads in the list.
edit:
Well, it's really lazy of you to not keep track of running threads. But, you can accomplish what you want by having a global var (protected by a mutex) that gets incremented just before a thread finishes. Then in you main thread you can check if that var gets to the value you want. Say nThreads in your sample code.
You need to join each thread you create:
int main()
{
int nThreads = sample(1,10);
std::vector<pthread_t> threads(nThreads);
for(i=0; i<nThreads; i++)
{
pthread_create( &threads[i], NULL, worker, (void*) i)
}
/* Wait on the other threads */
for(i=0; i<nThreads; i++)
{
status* status;
pthread_join(threads[i], &status);
}
}
You learned your assumption was wrong. Main is special. Exiting main will kill your threads. So there are two options:
Use pthread_exit to exit main. This function will allow you to exit main but keep other threads running.
Do something to keep main alive. This can be anything from a loop (stupid and inefficient) to any blocking call. pthread_join is common since it will block but also give you the return status of the threads, if you are interested, and clean up the dead thread resources. But for the purposes of keeping main from terminating any blocking call will do e.g. select, read a pipe, block on a semaphore, etc.
Since Martin showed join(), here's pthread_exit():
int main(){
int nThreads = sample(1,10);
for(int i=0;i<nThreads;i++){
fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
pthread_detach(thread1);
}
pthread_exit(NULL);
}