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

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

Difei Zhao wrote:

  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!

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

Frederick Cheung wrote:

Difei Zhao wrote:

Frederick Cheung 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.