473,804 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

synchronizing 3 threads

I am trying to teach myself more about synchronizing threads. I took
the following code from a book and have altered it to read one more
file (the program counts in the words in multiple files). The
original program from the book counted the words in 2 files. I want
to increase that to 3. However, when I add the 3rd thread it just
gets to a certain point and hangs. I think that the answer is to add
another condition variable, however, I can't quite grasp how I would
use this other variable. Can someone point me in the right direction?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
struct arg_set {
char *fname;
int count;
};

struct arg_set *mailbox;
pthread_mutex_t lock = PTHREAD_MUTEX_I NITIALIZER;
pthread_cond_t flag = PTHREAD_COND_IN ITIALIZER;

int main( int ac, char *av[] )
{
pthread_t t1, t2, t3;
struct arg_set args1, args2, args3;
void *count_words(vo id *);
int reports_in = 0;
int total_words = 0;

if(ac != 4) {
printf("usage: %s file1 file2 file3\n", av[0]);
exit(1);
}

pthread_mutex_l ock(&lock);

args1.fname = av[1];
args1.count = 0;
pthread_create( &t1, NULL, count_words, (void *) &args1);

args2.fname = av[2];
args2.count = 0;
pthread_create( &t2, NULL, count_words, (void *) &args2);

args3.fname = av[3];
args3.count = 0;
pthread_create( &t3, NULL, count_words, (void *) &args3);

while(reports_i n < 3) {
printf("MAIN: waiting for flag to go up\n");
pthread_cond_wa it(&flag, &lock);
printf("Main: Wow! flag was raised, I have the lock\n");
printf("%7d: %s\n", mailbox->count, mailbox->fname);
total_words += mailbox->count;
if(mailbox == &args1)
pthread_join(t1 , NULL);
if(mailbox == &args2)
pthread_join(t2 , NULL);
if(mailbox == &args3)
pthread_join(t3 , NULL);
mailbox = NULL;
pthread_cond_si gnal(&flag);
reports_in++;
}
printf("%7d: total words\n", total_words);
}

void * count_words(voi d *a)
{
struct arg_set *args = a;
FILE *fp;
int c, prevc = '\0';

if((fp = fopen(args->fname, "r")) != NULL) {
while((c = getc(fp)) != EOF) {
if(!isalnum(c) && isalnum(prevc))
args->count++;
prevc = c;
}
fclose(fp);
}
else
perror(args->fname);
printf("COUNT: waiting to get lock\n");
pthread_mutex_l ock(&lock);
printf("COUNT: have lock, storing data\n");
if(mailbox != NULL)
pthread_cond_wa it(&flag, &lock);
mailbox = args;
printf("COUNT: raising flag\n");
pthread_cond_si gnal(&flag);
printf("COUNT: unlocking box\n");
pthread_mutex_u nlock(&lock);

return NULL;
}

Apr 6 '07 #1
7 1380
On 5 Apr 2007 20:12:30 -0700, "iwasinniho n" <iw*********@ho tmail.com>
wrote in comp.lang.c:
I am trying to teach myself more about synchronizing threads.
[snip]

You're asking in the wrong place. Threads are not defined by, or part
of, the C language. They are extensions provided by your particular
operating system.

Ask in news:comp.progr amming.threads, or an OS specific group, perhaps
news:comp.os.li nux.development or news:comp.unix. programmer. Or a
Windows group like news:comp.os.ms-windows.program mer.win32.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Apr 6 '07 #2
Inspecting your code I do not find anything obviously wrong.

It would be helpful to know what happens really, i.e. what
is the sequence of printf outputs when you "fail". You say:
"It hangs" but it is not helpful for anyone trying to
figure out what happens.

jacob
Apr 6 '07 #3
In article <11************ **********@n76g 2000hsh.googleg roups.com>,
iwasinnihon <iw*********@ho tmail.comwrote:
>I am trying to teach myself more about synchronizing threads. I took
Off topic. Not portable. Cant discuss it here. Blah, blah, blah.

Useful clc-related links:

http://en.wikipedia.org/wiki/Aspergers
http://en.wikipedia.org/wiki/Clique
http://en.wikipedia.org/wiki/C_programming_language

Apr 6 '07 #4
"Kenny McCormack" <ga*****@xmissi on.xmission.com ha scritto nel messaggio
news:ev******** **@news.xmissio n.com...
In article <11************ **********@n76g 2000hsh.googleg roups.com>,
iwasinnihon <iw*********@ho tmail.comwrote:
>>I am trying to teach myself more about synchronizing threads. I took

Off topic. Not portable. Cant discuss it here. Blah, blah, blah.

Useful clc-related links:

http://en.wikipedia.org/wiki/Aspergers
http://en.wikipedia.org/wiki/Clique
http://en.wikipedia.org/wiki/C_programming_language
Empty posts serve no purpose, and signatures should begin with
<newline>--<newline>. And check wheter there are some missing apostrophes in
yours. :-)
Apr 6 '07 #5
"Army1987" <pl********@for .itwrites:
"Kenny McCormack" <ga*****@xmissi on.xmission.com ha scritto nel messaggio
news:ev******** **@news.xmissio n.com...
[snip]
Empty posts serve no purpose, and signatures should begin with
<newline>--<newline>. And check wheter there are some missing apostrophes in
yours. :-)
Please don't feed the troll.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 6 '07 #6
Army1987 wrote:

Empty posts serve no purpose, and signatures should begin with
<newline>--<newline>. And check wheter there are some missing
apostrophes in yours. :-)
Besides what Keith said, your information about .sig separators is
wrong. The standard is (using your descriptive method) is:
<newline>-- <newline>
That space is a vital component.


Brian
Apr 6 '07 #7
iwasinnihon wrote:
>
I am trying to teach myself more about synchronizing threads.
....

Threads are off topic here. Look for a newsgroup with 'thread' in
its name.

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfoc us.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews

--
Posted via a free Usenet account from http://www.teranews.com

Apr 7 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2536
by: Keith Veleba | last post by:
Hello to all fellow c.l.p'ers! Long-time listener, first-time caller. Background: I'm working on a project where I have to do some serious multithreading. I've worked up a decorator in Python 2.3.4 to implement the lock semantics required for specific functions I want to synchronize:
0
1985
by: SQLServer007 | last post by:
25 more days until the "get it free" promotion runs out for xSQL Object (you can get it from http://www.x-sql.com) Here are just some of the great features packed in the product: - Compare SQL Server objects (databases, tables, views, stored procedures, user defined data functions etc.) accross servers. - view and print dependencies; - generate color coded scripts for any object in the database or many of them at once (many configurable...
9
5488
by: Ralph Cramden | last post by:
I'm writing a VB6 app which calls several stored procedures on my SQL Server DB. The first stored procedure must complete its inserts before the second stored procedure can query the modified table for its results. My problem is that the second stored procedure occasionally returns a different result set, acting as if the first stored procedure didn't complete (or didn't run).
1
1563
by: Phil Matish, MCSE | last post by:
I have an Access database that I use frequently. Often, I take it to a home PC, or laptop to work on at night. The next day, I overwrite the old one with the one I have been working on. The only problem is - during this time, others may want to add records at the office. This causes an obvious data loss problem if I overwrite their edition of the database. Is there a way to synchronize the database? If someone made additions at...
2
4657
by: Chuck | last post by:
I have not been able to find a good answer about the System.Collections.Queue.Synchronized() method and how it actually works or is to be used. If I create my Queue in the following manner: System.Collections.Queue myQueue = System.Collections.Queue.Synchronized(new System.Collections.Queue()); is it a Thread-Safe queue no matter where it is used? Or do I have to call
2
3721
by: Christopher D. Wiederspan | last post by:
We are getting ready to move an ASP.NET application off of a single development machine and onto a "webfarm". Basically our webfarm is a bunch of identical servers with the load-balancing provided by a network appliance. What I'm wondering is what is the best way to keep the ASP.NET (.aspx and .dll) files synchronized across all of the servers in the farm. Our ASP.NET application is very simple - we could just copy the content to all of...
0
963
by: Salamandras | last post by:
Greetings I would like some help on achieving synchronization between multiple threads running a for loop. In more detail I would like each thread to be in the same iteration with each other thread, meaning no thread would be in the fifth iteration when another is in the second or in the first... So the results would go Thread1 = iteration 1 Thread2 = iteration 1 Thread3 = iteration 1 Thread4 = iteration 1 Thread1 = iteration 2 Thread2...
1
1177
by: mczard | last post by:
In my application events can be raised in one thread, but delegates can be added to the events from another thread. I wonder if I really have to synchronize the event raising and all += / -= operations. Do I have to write: lock ( source.NewInput ) { source.NewInput += this.NewInputHandler; }
8
8504
by: colin | last post by:
Hi, this probaly isnt the most relevant place to ask this, but Im using a windows forms in c# timer to process user input and invalidate a window if its changed. Im having problems in that the OnPaint messages arnt synchronized to the vertical refresh wich from what I read I had understood that there was supposed to be some synchronization. im using directx to draw the window, its a 3d model editor
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10096
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7638
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6866
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.