About transaction do..end block (or critical section)

Greetings all,

Does the transaction do…end block guaranteed a critical section or
just a database transaction? I want to save some file to the file system
and then save the file path to a DB table, there are race conditions
because other rails process/thread may create a file with a same name
and this application may destroy the file by overwrite it. I want to
construct a critical section like:

/* critical section do /
file_path = generate_filepath
some_process if file_path.exist?
dbrec1.file_path = file_path
dbrec1.save
dbrec2.save
File.write(file_path)
/
end */

How can I achieve this? Thanks very much!

Cheers,
Difei

On 4 Sep 2008, at 19:19, Difei Z. [email protected]
wrote:

Greetings all,

Does the transaction do…end block guaranteed a critical section or
just a database transaction?

Just a database transaction

I want to save some file to the file system
and then save the file path to a DB table, there are race conditions
because other rails process/thread may create a file with a same name
and this application may destroy the file by overwrite it. I want to
construct a critical section like:

Open the file with an exclusive lock?

Fred

Frederick C. wrote:

On 4 Sep 2008, at 19:19, Difei Z. [email protected]
wrote:

Greetings all,

Does the transaction do…end block guaranteed a critical section or
just a database transaction?

Just a database transaction

I want to save some file to the file system
and then save the file path to a DB table, there are race conditions
because other rails process/thread may create a file with a same name
and this application may destroy the file by overwrite it. I want to
construct a critical section like:

Open the file with an exclusive lock?

Fred

Thank you all.
But I think something like:

File.new(“blabla”, File::CREAT|File::WRONLY).flock

is not atomic and may lock the file generated by aother process/thread?

Difei Z. wrote:

Frederick C. wrote:

File.new(“blabla”, File::CREAT|File::WRONLY).flock

is not atomic and may lock the file generated by aother process/thread?

I overlooked the O_EXCL, thanks all.

Difei Z. wrote:

dbrec1.file_path = file_path
dbrec1.save
dbrec2.save
File.write(file_path)
/* end */

How can I achieve this? Thanks very much!

Perhaps by using a lock file, either with File::flock, or the
NFS-safe lockfile library:

http://raa.ruby-lang.org/project/lockfile/1.3.0


Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com